Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example 1:
Given 1->2->3->4, reorder it to 1->4->2->3.
Example 2:
Given 1->2->3->4->5, reorder it to 1->5->2->4->3.
分析:
(1)求得链表长度;
(2)根据链表长度求后半段链表
(3)对后半段链表反转
(4)将两段链表连起来
代码:
public void reorderList(ListNode head) {
int len = getlLength(head);
if (len<=2) {
return;
}
ListNode lastBeforeCut = findLastBeforeCut(head, len/2);
ListNode tail = lastBeforeCut.next;
lastBeforeCut.next = null;
ListNode reversedTail = reverse(tail);
zip(head, reversedTail);
}
private int getLength(ListNode head) {
int len = 0;
while (head != null) {
++len;
head = head.next;
}
return len;
}
private ListNode findLastBeforeCut(ListNode head, int cut) {
int i = 0;
while (i < cut) {
++i;
head = head.next;
}
return head;
}
private ListNode reverse(ListNode head) {
ListNode current = head, prev = null, tmp = null;
while (current != null) {
tmp = current.next;
current.next = prev;
prev = current;
current = tmp;
}
return prev;
}
private void zip(ListNode head1, ListNode head2) {
while (head2 != null) {
ListNode next1 = head1.next;
ListNode next2 = head2.next;
head1.next = head2;
head2.next = next1;
head1 = next1;
head2 = next2;
}
}