题目如下:
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) +1, 第二部分取剩余的。 分割后的两个链表都要将末尾置为NULL。
这种分割方法,需要先遍历链表长度,再进行分割,需要遍历两次链表。因此可以改进成采用快慢节点取得中间节点的方式,只要一遍遍历即可。
(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) {
//采用快慢节点找中间节点的方式
if(head == null || head.next == null || head.next.next == null) return;
ListNode Head = split(head);
merge(head, Head);
}
private int length(ListNode head){
int len = 0;
ListNode p = head;
while(p != null){
len++;
p = p.next;
}
return len;
}
private ListNode split(ListNode head, int len){
int splitPos = (len / 2) + 1;
ListNode p = head;
splitPos--;
while(splitPos != 0){
p = p.next;
splitPos--;
}
ListNode Head = p.next;
p.next = null;
return reverse(Head);
}
private ListNode split(ListNode head){
ListNode slow = head;
ListNode fast = slow.next;
while(fast.next != null && fast.next.next != null)
slow = slow.next;
fast = fast.next.next;
}
slow = slow.next;
ListNode Head = slow.next;
slow.next = null;
return reverse(Head);
}
private ListNode reverse(ListNode p){
if(p == null || p.next == null) return p;
ListNode current = p.next;
p.next = null;
while(current != null){
ListNode temp = current;
current = current.next;
temp.next = p;
p = temp;
}
return p;
}
private void merge(ListNode p, ListNode q){
ListNode current = p;
while(q != null){
ListNode temp = q;
q = q.next;
temp.next = current.next;
current.next = temp;
current = current.next.next;
}
}
}