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}
.
思路:
1.利用快慢两个指针将链表一分为二;
2.针对第二个子链表求倒序;
3.利用merge思想将两个子链表合并。
代码:
public class ReorderSingleList {
/**
* Definition for singly-linked list. class ListNode { int val; ListNode
* next; ListNode(int x) { val = x; next = null; } }
*/
public void reorderList(ListNode head) {
if (head == null || (head.next == null)) {
return;
}
// fast and slow point find the mid position.
ListNode fast = head;
ListNode slow = head;
while ((fast != null) && (fast.next != null)) {
fast = fast.next.next;
slow = slow.next;
} // reverse the last second list.
ListNode headnode = new ListNode(-1);
headnode.next = slow;
ListNode temp = headnode.next;
while (temp.next != null) {
ListNode insert = temp.next;
ListNode currNext = insert.next;
insert.next = headnode.next;
headnode.next = insert;
temp.next = currNext;
} // merge insert
ListNode firstcur = head;
ListNode secondcur = headnode.next;
while (firstcur != slow && (secondcur != slow)) {// at first,I make a mistake in here;
ListNode firstnex = firstcur.next;
ListNode secondnex = secondcur.next;
firstcur.next = secondcur;
secondcur.next = firstnex;
firstcur = firstnex;
secondcur = secondnex;
}
} public static void main(String[] args) {
ListNode t5 = new ListNode(5);
ListNode t4 = new ListNode(4, t5);
ListNode t3 = new ListNode(3, t4);
ListNode t2 = new ListNode(2, t3);
ListNode t1 = new ListNode(1, t2);
new ReorderSingleList().reorderList(t1);
System.out.println(t1);
} }