• [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;
            }
        }    
    };
    

      

  • 相关阅读:
    BUG漏测的原因总结,以及如何处理
    费用流
    拉格朗日插值
    数论问题整理
    计数问题
    POJ 1741 Tree
    bzoj 2820: YY的GCD
    luogu P3690 【模板】Link Cut Tree (动态树)
    bzoj 1036: [ZJOI2008]树的统计Count
    bzoj 3282: Tree
  • 原文地址:https://www.cnblogs.com/lautsie/p/3456645.html
Copyright © 2020-2023  润新知