Question:
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal tox.
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
.
分析:
建立两个list,一大一小,小的存储小于x的节点,大的存储大于x的节点,两个相连然后返回小链表表头,即解。
Code:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode partition(ListNode head, int x) {
// Start typing your Java solution below
// DO NOT write main() function
ListNode small = new ListNode(0);
ListNode big = new ListNode(0);
ListNode s = small, b = big, c = head;
while(c != null){
if(c.val < x){
s.next = c;
s = s.next;
c = c.next;
s.next = null;
}
else{
b.next = c;
b = b.next;
c = c.next;
b.next = null;
}
}
s.next = big.next;
return small.next;
}
}
总结:
必须特别注意的地方是每次加到小链表或大链表后,要把小/大链表的尾节点指向null,防止循环链表出现。