86. Partition List
/** * 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) { ListNode dummy1 = new ListNode(-1); ListNode dummy2 = new ListNode(-1); ListNode cur1 = dummy1; ListNode cur2 = dummy2; ListNode cur = head; while( cur != null ){ if( cur.val < x){ cur1.next = cur; cur1 = cur1.next; }else{ cur2.next = cur; cur2 = cur2.next; } cur = cur.next; } cur2.next = null; cur1.next = dummy2.next; return dummy1.next; } }
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
posted on 2018-07-18 09:20 猪猪🐷 阅读(83) 评论(0) 收藏 举报
浙公网安备 33010602011771号