leetcode 143. Reorder List

这道理考察链表的综合知识很全面详细,需要转换链表,那么看一下需要经过的步骤的:

首先需要寻找到链表的中点,这个可以使用快慢指针的;

然后是对于下一个链表需要进行反转,这里有两个做法,一种是新建头结点另外一种是不新建头结点的;

最后是两个链表的相互连接。

/**
 * 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 || !head->next || !head->next->next) return;
        
        ListNode* fast,*slow;
        //ListNode *res=new ListNode(-1);
        //ListNode *p=res;
        fast=slow=head;
        while(fast && fast->next){
            slow=slow->next;
            fast=fast->next->next;
        }
        ListNode* p=slow->next;
        slow->next=NULL;
        ListNode* last=p;
        ListNode* pre=NULL;
        while(last){
            ListNode* cur=last->next;
            last->next=pre;
            pre=last;
            last=cur;
        }
        while(head && pre){
            ListNode* temp=head->next;
            head->next=pre;
            pre=pre->next;
            head->next->next=temp;
            head=temp;
        }
    }
};

 

posted on 2018-09-11 21:41  昔风不止,唯有努力生存  阅读(103)  评论(0编辑  收藏  举报

导航