题目:
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.
思路:
两个链表,一个存小于x, 一个存大于或等于 x, 最后两个链表合并
Code:
public ListNode partition(ListNode head, int x) {
ListNode smaller = new ListNode(0);
ListNode sp = smaller;
ListNode greater = new ListNode(0);
ListNode gp = greater;
while(head != null){
ListNode temp = new ListNode(head.val);
if(head.val < x){
sp.next = temp;
sp = sp.next;
}else{
gp.next = temp;
gp = gp.next;
}
head = head.next;
}
sp.next = greater.next;
return smaller.next;
}
备注:
对于定义了构造函数的 class,在new时必须使用对应的构造函数!