题目:
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.
Example:
Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5
思路:
新建两个链表。l1和l2,比x小的都在l1
等于或者大于的都在l2,因为要保留原始位置吗
最后curr1.next = dummy2.next;curr2.next=null;
public ListNode partition(ListNode head, int x) {
’
ListNode dummy1 = new ListNode(0);
ListNode dummy2 = new ListNode(0);
ListNode curr1 = dummy1;
ListNode curr2 = dummy2;
while(head!=null){
if(head.val<x){
curr1.next = head;
curr1 = head;
}else{
curr2.next = head;
curr2 = head;
}
head = head.next;} curr2.next=null;
curr1.next = dummy2.next;
return dummy1.next;
}