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

      

  • 相关阅读:
    字符串删减
    iOS-AFNetworking与ASIHTTPRequest的区别
    iOS-清理缓存
    iOS-addSubView时给UIView添加效果
    iOS-明杰解决字段冲突,及数组映射
    iOS-开发将文本复制到剪切板
    iOS-加载html字符串
    iOS-UILabel加线
    iOS-获取webView的高度
    iOS-plist文件的写读
  • 原文地址:https://www.cnblogs.com/lautsie/p/3456645.html
Copyright © 2011-2022 走看看