zoukankan      html  css  js  c++  java
  • [leetcode]Reorder List

    此题有点意思,先用快慢指针把链表从一半处断开,然后把后半段倒过来,然后再进行merge。注意断开时要把前面链表的最后置NULL,merge后要把最后节点next置NULL。

    #include <string>
    #include <vector>
    #include <iostream>
    using namespace std;
    
    class Solution {
    public:
        ListNode * reverseList(ListNode *head) {
            if (head == NULL) return NULL;
            ListNode *dummy = new ListNode(0);
            dummy->next = head;
            ListNode *prev = dummy;
            ListNode *current = head;
            while (current != NULL) {
                ListNode *tmp = current->next;
                current->next = (prev == dummy ? NULL : prev);
                prev = current;
                current = tmp;
            }
            delete dummy;
            return prev;
        }
        void reorderList(ListNode *head) {
            if (head == NULL) return;
            ListNode *fast = head;
            ListNode *slow = head;
            do {
                if (fast == NULL || fast->next == NULL) break;
                fast = fast->next->next;
                slow = slow->next;
            } while (fast != slow);
            // disconnect the list from after slow
            ListNode *second = slow->next;
            slow->next = NULL;
            second = reverseList(second);
            ListNode *first = head;
            while (first != NULL && second != NULL) {
                ListNode *first_next = first->next;
                ListNode *second_next = second->next;
                first->next = second;
                second->next = first_next;
                first = first_next;
                second = second_next;
            }
            if (second != NULL) {
                second->next = NULL;
            }
        }    
    };
    

      

  • 相关阅读:
    二叉树解题思想
    SpringBoot + Mybatis 和ssm 使用数据库的区别
    Spring Cache 抽象(缓存抽象) Redis 缓存
    VirtualBox 虚拟机 从入门到入坑
    小知识点的记录
    SpringBoot 的不同
    请你激起学习的激情
    java 适配器模式
    UML类图的情话诉说
    Java 工厂模式
  • 原文地址:https://www.cnblogs.com/lautsie/p/3456645.html
Copyright © 2011-2022 走看看