• 143. Reorder List


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

    本题可以看做是Reverse Linked List 2的进一步复杂态,本题的解题思路是

    若链表为1 2 3 4 5 6 7 8 9

    1. 寻找链表的中间元素

    2. 将链表的后半段反序(利用Reverse Linked List 2的概念)

    3. 新得的链表1 2 3 4 5 9 8 7 6. 则对链表重新排序即可(亦利用Reverse Linked List 2,将后半段链表中的元素逐个插入到前半段,9插入到1,2之间;8插入到2,3之间......)

    在解题时,由于遗失移动位的后一位进行了长时间的debug

    因此,应该注意

    1.如果移除链表的某一位,必须线保存其后一位

    2.如果在链表的某一位进行添加,先保存其后一位

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public void reorderList(ListNode head) {
            
            if (head==null||head.next==null) return;
            
            ListNode p1 = head;
            ListNode p2 = head;
            while(p2.next != null && p2.next.next != null) {
                p1 = p1.next;
                p2 = p2.next.next;
            }
            
            ListNode pre = p1;
            ListNode curr = p1.next;
            ListNode middle = p1;
            while(curr.next != null) {
                ListNode then = curr.next;
                curr.next = then.next;
                then.next = pre.next;
                pre.next = then;
                then = curr.next;
            }
            
            ListNode start = head;
            ListNode move = middle.next;
            while(start != middle) {
                middle.next = move.next;
                move.next = start.next;
                start.next = move;
                start = move.next;
                move = middle.next;
            }
            
        }
    }
    

      

  • 相关阅读:
    python爬虫练习5——新闻联播
    python爬虫练习4——腾讯视频评论提取
    python爬虫练习3——豆瓣电影
    python爬虫练习2——豆瓣读书
    python爬虫练习1——百度阅读榜
    微信小程序音频视频下载(fiddler抓包)
    4. Median of Two Sorted Arrays
    42.trapping-rain-water
    3.lengthOfLongestSubstring
    1.two sum
  • 原文地址:https://www.cnblogs.com/Raymond-Yang/p/5213828.html
Copyright © 2020-2023  润新知