- -就是把链表分成两半
然后把后面的间隔插入到第一个里面
当然后面的最好是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; } };