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
.
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public ListNode partition(ListNode head, int x) { 11 if(head == null) return head; 12 ListNode pre1 = new ListNode(0); 13 ListNode pre2 = new ListNode(0); 14 ListNode L1 = pre1; 15 ListNode L2 = pre2; 16 while(head != null){ 17 if(head.val < x){ 18 L1.next = head; 19 L1 = L1.next; 20 }else{ 21 L2.next = head; 22 L2 = L2.next; 23 } 24 head = head.next; 25 } 26 L2.next = null; 27 L1.next = pre2.next; 28 return pre1.next; 29 } 30 }
时间: 2024-10-10 02:06:23