Last active
December 29, 2015 13:39
-
-
Save junjiah/7679041 to your computer and use it in GitHub Desktop.
solved 'Reorder List' on LeetCode (ONE AC! oh yeah;) http://oj.leetcode.com/problems/reorder-list/
This file contains 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 singly-linked list. | |
* class ListNode { | |
* int val; | |
* ListNode next; | |
* ListNode(int x) { | |
* val = x; | |
* next = null; | |
* } | |
* } | |
*/ | |
public class Solution { | |
public void reorderList(ListNode head) { | |
// IMPORTANT: Please reset any member data you declared, as | |
// the same Solution instance will be reused for each test case. | |
if (head == null) return; | |
List<ListNode> l = new ArrayList<ListNode>(); | |
ListNode iter = head.next; | |
while (iter != null) { | |
l.add(iter); | |
iter = iter.next; | |
} | |
iter = head; | |
int i = l.size()-1; | |
while (i>=0 && l.get(i) != iter) { | |
ListNode tmp = iter.next; | |
iter.next = l.get(i); | |
if (iter.next == tmp) { | |
i = 0; // break | |
} | |
else { | |
iter.next.next = tmp; | |
} | |
iter = tmp; | |
i--; | |
} | |
iter.next = null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment