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}.
/**
* 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;
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode temp = slow.next;
slow.next = null;
slow = temp;
ListNode head2 = new ListNode(0);
while (slow != null) {
temp = slow;
slow = slow.next;
temp.next = head2.next;
head2.next = temp;
}
ListNode pointer1 = head;
ListNode pointer2 = head2.next;
while (pointer1 != null && pointer2 != null) {
temp = pointer2.next;
pointer2.next = pointer1.next;
pointer1.next = pointer2;
pointer1 = pointer1.next.next;
pointer2 = temp;
}
return;
}
}
链表重组算法
本文介绍了一种链表重组算法,该算法将一个单链表重新排列,使得原链表的节点按照特定顺序交错排列。文章详细阐述了实现过程,包括寻找中间节点、反转后半部分链表以及交错合并两个链表。
360

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



