Leetcode86. Partition List
题挺好的,就是题意容易引起误解:其实问题就是让链表中小于x的结点出现在大于等于x节点的左边,并保持原有顺序(稳定)。
如:
Input: head = 2->4->3->1->5->2, x = 3
Output: 2->1->2->4->3->5
题不算难,只要分析好节点交换时需要记录哪些节点,别让链断掉就好。
另外链表找next的时候需要时刻注意,p.next是否为null,避免出现NullPointerError。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode partition(ListNode head, int x) {
if(head==null) return null;
ListNode dummy = new ListNode(-1);
ListNode pre = dummy;
pre.next = head;
//pre后面就是我们要往里填小于x的节点的位置
while(pre.next!=null&&pre.next.val<x) pre=pre.next;
if(pre.next==null) return dummy.next;
ListNode p = pre;
while(p.next!=null){
while(p.next!=null&&p.next.val>=x) p = p.next; //p后面是我们要填到前面的节点
if(p.next==null) break; //判断是否已经找到结尾
ListNode temp = p.next;
p.next = p.next.next;
temp.next = pre.next;
pre.next = temp;
pre = temp;
}
return dummy.next;
}
}
Runtime: 0 ms, faster than 100.00% of Java online submissions for Partition List.
Memory Usage: 37 MB, less than 17.28% of Java online submissions for Partition List.