您的位置:首页 > 其它

LeetCode Partition List

2015-09-01 04:28 387 查看
原题链接在这里:https://leetcode.com/problems/partition-list/

思路: 从头到尾每当发现大于等于x的点,就删掉加在list尾部。

Note: 1. 建立一个dummy head放在链表头用来处理原有head.val大于等于x的边界情况。

2.用一个mark标注原有的tail,while loop 的条件是iter.next != mark 而不是 iter.next != null,因为一直往后加,是不会出来
null的,会陷入infinite loop.

3. 最要要注意mark本身还没有被检查过,所以要检查mark本身。

AC Java:

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode partition(ListNode head, int x) {
if(head == null || head.next == null){
return head;
}
ListNode dunmy = new ListNode(0);
dunmy.next = head;
ListNode iter = dunmy;
ListNode tail = head;
while(tail.next != null){
tail = tail.next;
}
ListNode mark = tail;
while(iter.next != mark){
if(iter.next.val >= x){
ListNode temp = new ListNode(iter.next.val);
tail.next = temp;
tail = tail.next;
iter.next = iter.next.next;
}else{
iter = iter.next;
}
}
if(iter.next.val >= x){
ListNode temp = new ListNode(iter.next.val);
tail.next = temp;
tail = tail.next;
iter.next = iter.next.next;
}
return dunmy.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: