zoukankan      html  css  js  c++  java
  • Leetcode 143. Reorder List(Medium)

    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}.

     搞了一天多,纠结到一个while 写成了if...........

    思路很清晰,  找出链表的中点,翻转第二个链表,合并两个链表。

    b 站视频讲解  

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* findMid(ListNode* head){   // 找出链表的中点,快慢指针解决,很经典。
            /*if (head == NULL || head -> next == NULL){
                return head;
            }*/
            ListNode* slow = head;
            ListNode* fast = head;
            while (fast != NULL && fast -> next != NULL){    // 注意判断条件很容易出问题
                slow = slow -> next;
                fast = fast -> next -> next;
            }
            return slow;
        }
        ListNode* reverseList(ListNode* head){   // 翻转一个链表
            ListNode* newhead = NULL;
            while (head != NULL){                //  一开始写成了if 纠结了一天,长记性。。。
                ListNode* nextp = head -> next;
                head -> next = newhead;
                
                newhead =  head;   // 统一后移
                head = nextp;
            }
            return newhead;
        }
        ListNode* merge(ListNode* l1, ListNode* l2){   // 合并两个链表
            if (l2 == NULL){
                return l1;
            }
            ListNode* head = l1;
            
            while (l1 != NULL && l2 != NULL){
                ListNode* nextp = l1 -> next;
                l1 -> next = l2;
                l2 = l2 -> next;
                l1 -> next -> next = nextp;
                
                l1 =  nextp;     //  l1后移
            }
            return head;
        }
        void reorderList(ListNode* head) {
            if (head == NULL || head -> next == NULL){
                return;
            }
            ListNode* mid = findMid(head);   // 1.找到链表的中点 
            ListNode* l1 = head;
            ListNode* l2 = mid -> next;     
            mid -> next = NULL;              // 2. 断开链表
            l2 = reverseList(l2);            // 3. 翻转l2
            head = merge(l1, l2);            // 4. 合并两个链表
        }
    };
  • 相关阅读:
    unity3d 打包个人记录
    Unity3d 协程
    Unity3d 复制文字到剪切板及存储图像到相册
    为什么 redo log 具有 crash-safe 的能力,是 binlog 无法替代的?
    Java源码系列4——HashMap扩容时究竟对链表和红黑树做了什么?
    深入理解Java虚拟机1——内存区域
    Java源码系列3——LinkedHashMap
    深入理解Java虚拟机2——对象探秘
    高效学习
    WordPress自动代码高亮
  • 原文地址:https://www.cnblogs.com/simplepaul/p/7738916.html
Copyright © 2011-2022 走看看