Created
June 4, 2015 15:26
-
-
Save cangoal/9e31572b06dea731a88d to your computer and use it in GitHub Desktop.
LeetCode - Partition List
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
| // | |
| public ListNode partition(ListNode head, int x) { | |
| if(head == null) return head; | |
| ListNode dummyNode = new ListNode(0); | |
| dummyNode.next = head; | |
| ListNode first = dummyNode, second = null; | |
| while(head != null){ | |
| if(head.val >= x){ | |
| if(second == null){ | |
| second = head; | |
| } else { | |
| second = second.next; | |
| } | |
| head = head.next; | |
| } else{ | |
| if(second == null){ | |
| head = head.next; | |
| } else { | |
| ListNode next = head.next; | |
| head.next = first.next; | |
| first.next = head; | |
| head = next; | |
| second.next = head; | |
| } | |
| first = first.next; | |
| } | |
| } | |
| return dummyNode.next; | |
| } | |
| // | |
| public ListNode partition(ListNode head, int x) { | |
| if(head==null) return null; | |
| ListNode helper = new ListNode(0); | |
| helper.next = head; | |
| ListNode pre = helper; | |
| ListNode cur = helper; | |
| while(cur.next!=null){ | |
| if(cur.next.val<x){ | |
| if(pre!=cur){ | |
| ListNode next = cur.next.next; | |
| cur.next.next = pre.next; | |
| pre.next = cur.next; | |
| cur.next = next; | |
| }else{ | |
| cur = cur.next; | |
| } | |
| pre = pre.next; | |
| }else{ | |
| cur = cur.next; | |
| } | |
| } | |
| return helper.next; | |
| } | |
| // | |
| public ListNode partition(ListNode head, int x) { | |
| if(head==null) return null; | |
| ListNode helper1 = new ListNode(0); | |
| ListNode helper2 = new ListNode(0); | |
| ListNode pre1 = helper1; | |
| ListNode pre2 = helper2; | |
| while(head!=null){ | |
| if(head.val<x){ | |
| helper1.next = head; | |
| helper1 = helper1.next; | |
| }else{ | |
| helper2.next = head; | |
| helper2 = helper2.next; | |
| } | |
| head = head.next; | |
| } | |
| helper2.next = null; | |
| helper1.next = pre2.next; | |
| return pre1.next; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment