1957

无聊蛋疼的1957写的低端博客
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

[leetcode]Reorder List

Posted on 2013-12-26 15:01  1957  阅读(219)  评论(0编辑  收藏  举报

- -就是把链表分成两半

然后把后面的间隔插入到第一个里面

当然后面的最好是reverse一下...不然每次去查找last会超时...

其实这个题,我遇到的最大的问题是...

reverseList竟然写错了...

就是链表的反转也能弄错...呵呵呵呵呵呵.....

 

那就复习下吧...两种方法,一种迭代,一种递归....

 

1,迭代

挨着把next置为prev就ok了

    ListNode* reverseList1(ListNode* head){
        if(head == nullptr || head -> next == nullptr) return head;
        ListNode* prev = nullptr;
        while(head){
            ListNode* next = head -> next;
            head -> next = prev;
            prev = head;
            head = next;
        }
        return prev;
    }

1,递归

似乎别迭代要难理解一点

就是吧链表看成

head.tail

递归的去reverse tail

而head的next正是tail反转过后的尾,所以

head -> next -> next = head

就是把head放到尾巴上去了...

    ListNode* reverseList(ListNode* head){
       if(head == nullptr || head -> next == nullptr) return head;
       ListNode* tmp = reverseList(head -> next);
       head -> next -> next = head;
       head -> next = nullptr;
       return tmp;
    }

全部代码如下:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    void reorderList(ListNode *head) {
        if(head == nullptr) return ;
        if(head -> next == nullptr) return;
        ListNode* fast = head;
        ListNode* slow = head;
        
        while(fast -> next && fast -> next -> next){
            fast = fast -> next -> next;
            slow = slow -> next;
        }
        
        ListNode* mid = slow -> next;
        slow -> next = nullptr;
        
        mid = reverseList1(mid);
        
        ListNode* newHead = head;
        while(newHead && mid){
            ListNode* insertNode = mid;
            mid = mid -> next;
            ListNode* next = newHead -> next;
            insertNode -> next = newHead -> next;
            newHead -> next = insertNode;
            newHead = next;
        }
    }
    ListNode* reverseList(ListNode* head){
       if(head == nullptr || head -> next == nullptr) return head;
       ListNode* tmp = reverseList(head -> next);
       head -> next -> next = head;
       head -> next = nullptr;
       return tmp;
    }
    ListNode* reverseList1(ListNode* head){
        if(head == nullptr || head -> next == nullptr) return head;
        ListNode* prev = nullptr;
        while(head){
            ListNode* next = head -> next;
            head -> next = prev;
            prev = head;
            head = next;
        }
        return prev;
    }
};