Created
February 15, 2013 07:02
-
-
Save daifu/4958913 to your computer and use it in GitHub Desktop.
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| 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. | |
| */ | |
| public ListNode partition(ListNode head, int x) { | |
| ListNode root = new ListNode(-1); | |
| ListNode pivot = new ListNode(x); | |
| ListNode root_last = root, pivot_last = pivot; | |
| ListNode cur_node = head; | |
| while (cur_node != null) { | |
| ListNode next = cur_node.next; | |
| if (cur_node.val < x) { | |
| root_last.next = cur_node; | |
| root_last = cur_node; | |
| } else { | |
| pivot_last.next = cur_node; | |
| pivot_last = cur_node; | |
| pivot_last.next = null; | |
| } | |
| cur_node = next; | |
| } | |
| root_last.next = pivot.next; | |
| return root.next; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment