Skip to content

Instantly share code, notes, and snippets.

@junjiah
Last active December 29, 2015 13:39
Show Gist options
  • Save junjiah/7679041 to your computer and use it in GitHub Desktop.
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/
/**
* 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