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.
思路:首先找到链表的中间节点,从中间断开链表,得到l1,l2;反转链表l2,然后顺序的将l2的节点插入到l1中;每隔一个节点插入一个。
源代码如下:
/**
* 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)
return ;
ListNode pslow = head, pfast = head;
while(pfast != null && pfast.next != null){
pslow = pslow.next;
pfast = pfast.next.next;
}
ListNode midNode = pslow.next;
pslow.next = null;
ListNode secondNode = reverse(midNode);
pslow = head;
pfast = secondNode;
while(pslow.next != null && pfast != null)
{
midNode = pfast;
pfast = pfast.next;
midNode.next = pslow.next;
pslow.next = midNode;
pslow = pslow.next.next;
}
if(pslow.next == null)
pslow.next = pfast;
}
ListNode reverse(ListNode head){
if(head == null || head.next == null)
return head;
ListNode current = head.next;
head.next = null;
while(current != null)
{
ListNode tmpNode = current;
current = current.next;
tmpNode.next = head;
head = tmpNode;
}
return head;
}
}