Created
September 1, 2015 17:03
-
-
Save cxtadment/2bdc73e3c9cf086a5b64 to your computer and use it in GitHub Desktop.
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
| /** | |
| * Definition for ListNode. | |
| * public class ListNode { | |
| * int val; | |
| * ListNode next; | |
| * ListNode(int val) { | |
| * this.val = val; | |
| * this.next = null; | |
| * } | |
| * } | |
| */ | |
| public class Solution { | |
| /** | |
| * @param head: The first node of linked list. | |
| * @param x: an integer | |
| * @return: a ListNode | |
| */ | |
| public ListNode partition(ListNode head, int x) { | |
| // write your code here | |
| // idea: use two pointer to record smaller partion and larger partion elements separately | |
| if (head == null) { | |
| return null; | |
| } | |
| ListNode leftDummy = new ListNode(0); | |
| ListNode left = leftDummy; | |
| ListNode rightDummy = new ListNode(1); | |
| ListNode right = rightDummy; | |
| while (head != null) { | |
| if (head.val < x) { | |
| left.next = head; | |
| left = left.next; | |
| } else { | |
| right.next = head; | |
| right = right.next; | |
| } | |
| head = head.next; | |
| } | |
| right.next = null; | |
| left.next = rightDummy.next; | |
| return leftDummy.next; | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment