-
Notifications
You must be signed in to change notification settings - Fork 0
86. Partition List
Jacky Zhang edited this page Oct 9, 2016
·
2 revisions
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given 1->4->3->2->5->2 and x = 3, return 1->2->2->4->3->5.
##Approach 1 解题思路为one pass,采用two pointers,一个连接小的部分,一个连接大的部分,再将两部分连接。
/**
* 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) {
ListNode smallerHead = new ListNode(0);
ListNode biggerHead = new ListNode(0);
ListNode smaller = smallerHead, bigger = biggerHead;
while(head != null) {
if(head.val < x) {
smaller.next = head;
smaller = smaller.next;
} else {
bigger.next = head;
bigger = bigger.next;
}
head = head.next;
}
smaller.next = biggerHead.next;
bigger.next = null;
return smallerHead.next;
}
}##Approach 2 记住小的那部分的尾节点,one pass链表,凡遇到小的节点,就把它从当前位置删除,插入到小的部分的尾节点之后。
/**
* 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) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode small = dummy;
ListNode pre = dummy;
ListNode cur = head;
while(cur != null) {
if(cur.val < x) {
if(pre == small) {
small = cur;
pre = pre.next;
cur = cur.next;
} else {
pre.next = cur.next;
cur.next = small.next;
small.next = cur;
small = cur;
cur = pre.next;
}
} else {
pre = pre.next;
cur = cur.next;
}
}
return dummy.next;
}
}