LeetCode Partition List

来源:互联网 发布:免费宣传片制作软件 编辑:程序博客网 时间:2024/06/10 01:04

原题链接在这里: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;    }}


0 0