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;
}
}

本文介绍了一种链表操作算法,通过求链表长度、分割、反转后半段链表并交替连接前后半段,实现链表元素的特定重组。此算法适用于链表长度大于2的情况。
359

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



