https://oj.leetcode.com/problems/reorder-list/
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes' values.
For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.
public void reorderList(ListNode head)
这一题其实就分三步去做。
第一步从中间分开两段,记得如果是长度为偶数则各一半,如果是奇数则左边比右边多一个。
第二步,将后半段reverse,就是普通的reverse list。
第三步,merge list。
下面就根据此把代码放上:
public void reorderList(ListNode head) {
if(head == null || head.next == null)
return;
ListNode sec_head = dividehelper(head);
sec_head = reversehelper(sec_head);
combinehelper(head, sec_head);
}
public ListNode dividehelper(ListNode head){
ListNode one_step = head, two_step = head, prev = null;
while(one_step != null && two_step != null){
prev = one_step;
one_step = one_step.next;
two_step = two_step.next == null ? two_step.next : two_step.next.next;
}
prev.next = null;
return one_step;
}
public ListNode reversehelper(ListNode head){
ListNode prev = null, tmp = head, next = tmp.next;
while(tmp != null){
next = tmp.next;
tmp.next = prev;
prev = tmp;
tmp = next;
}
return prev;
}
public void combinehelper(ListNode first, ListNode sec){
while(first != null && sec != null){
ListNode next_first = first.next;
ListNode next_sec = sec.next;
first.next = sec;
sec.next = next_first;
first = next_first;
sec = next_sec;
}
}
364

被折叠的 条评论
为什么被折叠?



