Partition List
lc86
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.
思路一是两个node,然后合并 感觉面试会这个思路即可
public ListNode partition(ListNode head, int x) {
if (head == null) {
return null;
}
ListNode leftDummy = new ListNode(0);
ListNode rightDummy = new ListNode(0);
ListNode left = leftDummy, right = rightDummy;
while (head != null) {
if (head.val < x) {
left.next = head;
left = head;
} else {
right.next = head;
right = head;
}
head = head.next;
}
right.next = null;
left.next = rightDummy.next;
return leftDummy.next;
}
思路二:用两个pointer
public ListNode partition(ListNode head, int x) {
if(head == null)
return null;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode walker = dummy;
ListNode runner = dummy;
while(runner.next!=null)
{
if(runner.next.val<x)
{
if(runner!=walker)
{
ListNode next = runner.next.next;
runner.next.next = walker.next;
walker.next = runner.next;
runner.next = next;
}
else
runner = runner.next;
walker = walker.next;
}
else
{
runner = runner.next;
}
}
return dummy.next;
}
与partition array的方法对笔着来
/**
* 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 head;
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode start = dummy;
head = dummy;
while(head.next != null) {
if (head.next.val < x) {
if (start != head) {
ListNode temp = start.next;
start.next = head.next;
ListNode temp2 = head.next.next;
head.next.next = temp;
start = start.next;
head.next = temp2;
} else {
head = head.next;
start = start.next;
}
} else {
head = head.next;
}
}
return dummy.next;
}
}