[leetcode]143. Reorder List重排链表

Given a singly linked list LL0→L1→…→Ln-1→Ln,
reorder it to: L0→LnL1→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.

题意:

按照头尾交替的方式重排一个链表

思路:

使用快慢指针找到链表中点,并将链表从中点处断开,形成2个独立的链表

将第2个链表翻转

扫描二维码关注公众号,回复: 1765612 查看本文章

将第2个链表的元素间隔地插入第1个链表

 代码:

 1 class Solution {
 2     public void reorderList(ListNode head){    
 3         if (head == null || head.next == null) return;
 4         ListNode slow = head, fast = head, prev = null;
 5         while (fast != null && fast.next != null) { 
 6             prev = slow;
 7             slow = slow.next;
 8             fast = fast.next.next;
 9         }
10         prev.next = null; // cut at middle
11 
12         slow = reverse(slow);
13 
14         // merge two lists
15         ListNode curr = head;
16         while (curr.next != null) {
17             ListNode tmp = curr.next;
18             curr.next = slow;
19             slow = slow.next;
20             curr.next.next = tmp;
21             curr = tmp;
22         }
23         curr.next = slow;
24     }
25 
26     ListNode reverse(ListNode head) {
27         if (head == null || head.next == null) return head;
28         ListNode prev = head;
29         for (ListNode curr = head.next, next = curr.next; curr != null;
30             prev = curr, curr = next, next = next != null ? next.next : null) {
31                 curr.next = prev;
32         }
33         head.next = null;
34         return prev;
35     }
36 }

猜你喜欢

转载自www.cnblogs.com/liuliu5151/p/9227177.html