LeetCode143 重排链表

给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

 

可以遍历然后存起来,然后空间换时间。

 

也可以递归,但是递归的方法需要巧妙一点。

这里借用windliang的解法,每次往内递归,把head指向tail,tail指向内部处理完的链表的第一个节点。

 

 1 public void reorderList(ListNode head) {
 2 
 3     if (head == null || head.next == null || head.next.next == null) {
 4         return;
 5     }
 6     int len = 0;
 7     ListNode h = head;
 8     //求出节点数
 9     while (h != null) {
10         len++;
11         h = h.next;
12     }
13 
14     reorderListHelper(head, len);
15 }
16 
17 private ListNode reorderListHelper(ListNode head, int len) {
18     if (len == 1) {
19         ListNode outTail = head.next;
20         head.next = null;
21         return outTail;
22     }
23     if (len == 2) {
24         ListNode outTail = head.next.next;
25         head.next.next = null;
26         return outTail;
27     }
28     //得到对应的尾节点,并且将头结点和尾节点之间的链表通过递归处理
29     ListNode tail = reorderListHelper(head.next, len - 2);
30     ListNode subHead = head.next;//中间链表的头结点
31     head.next = tail;
32     ListNode outTail = tail.next;  //上一层 head 对应的 tail
33     tail.next = subHead;
34     return outTail;
35 }
36 
37 作者:windliang
38 链接:https://leetcode-cn.com/problems/reorder-list/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by-34/
39 来源:力扣(LeetCode)
40 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

第三种方法就是先拆分链表成两半,然后把后半部分翻转,然后两个链表合并。

 

posted @ 2020-07-23 22:33  __rookie  阅读(184)  评论(0编辑  收藏  举报