/**
* 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) {
ListNode faster = new ListNode(-1);
ListNode slower = new ListNode(-1);
faster = head; slower = head;
if(faster == null)
return;
if(faster.next == null) return;
while(faster.next != null && faster.next.next != null){
faster = faster.next.next;
slower = slower.next;
}
ListNode head2 = slower.next;
slower.next = null;
ListNode cur1=head, cur2=reverseList(head2);
if(cur2 == null)
return;
ListNode next1, next2;
while(cur1!=null && cur2 != null){
next1 = cur1.next;
next2 = cur2.next;
cur1.next = cur2;
cur2.next = next1;
cur1 = next1;
cur2 = next2;
}
}
private ListNode reverseList(ListNode head) {
if(head == null)
return null;
ListNode cur = head.next;
if(cur == null)
return head;
head.next = null;
while(cur != null) {
ListNode nd = cur.next;
cur.next = head;
head = cur;
cur = nd;
}
return head;
}
}
分析:画个图出来:当开头节点始终连向尾巴,尾巴始终联接开头。开头后移,尾巴前移,直到开头遇到尾巴。但是这里尾巴前移增加了算法的复杂度,此方法不符合题目要求。
还有一个,就是1,从中间切分;2,颠倒第二部分;3,一一连接两个部分的节点
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}
.