Recorder_List
https://www.nowcoder.com/questionTerminal/3d281dc0b3704347846a110bf561ef6b
Given a singly linked list L: L
0→L
1→…→L
n-1→L
n,
reorder it to: L
0→L
n
→L
1→L
n-1→L
2→L
n-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}.
public void reorderList(ListNode head) {
if(head==null||head.next==null)
return ;
//快慢指针发找到中间结点。
ListNode walker=head;
ListNode runner=head;
while(runner.next!=null&&runner.next.next!=null){
walker=walker.next;
runner=runner.next.next;
}
//反转中间结点后面的链表采用头插法
ListNode after=walker.next;
walker.next=null;
ListNode pre=null;
while(after!=null){
ListNode temp=after.next;
after.next=pre;
pre=after;
after=temp;
}
//将两个链表进行合并
ListNode first=head;
ListNode last=pre;
while(first!=null&&last!=null){
ListNode p=first.next;
ListNode q=last.next;
first.next=last;
first=p;
last.next=first;
last=q;
}
}
/*
*
* ListNode helper=new ListNode(0);
ListNode cur=head;
ListNode pre=helper;
while(cur!=null){
head=head.next;//保存要插入链表的位置
pre.next=cur;
pre=cur;
ListNode last=head;
while(last!=null&&last.next!=null){
last=last.next;
}
cur=last;
}自己开始想的思路不行:建一个新的单链表,一个head指针指向链表头,last指针指向链表尾,将head指向的结点和last指向的结点依次插入单链表中
* */
本题解题思路:
1.采用快慢指针方法找到中间结点,从中间结点断开为两个单链表;
2.将中间结点后面的单链表进行逆序,采用头插法;
3.合并前后两个单链表。