Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example 1:
Given 1->2->3->4, reorder it to 1->4->2->3.
Example 2:
Given 1->2->3->4->5, reorder it to 1->5->2->4->3.
题目大意:
给定链表,对链表进行重排序。使得 L0→Ln→L1→Ln-1→L2→Ln-2→…。
解法:
1.使用快慢指针找到中间节点
2.将后半部分链表翻转
3.将链表重新拼接
java:
class Solution { public void reorderList(ListNode head) { if(head==null) return; ListNode p=head,q=head; //找到链表的中间节点p while(q.next!=null&&q.next.next!=null) { p = p.next; q = q.next.next; } //将后半部分链表翻转 ListNode preMiddle=p; ListNode pre=null; ListNode cur=p.next; while(cur!=null){ ListNode next=cur.next; cur.next=pre; pre=cur; cur=next; } preMiddle.next=pre; //将链表重新拼接 p=head; q=preMiddle.next; while(p!=preMiddle){ preMiddle.next=q.next; q.next=p.next; p.next=q; p=q.next; q=preMiddle.next; } } }