【Leetcode】Reorder List

来源:互联网 发布:快乐识字软件 编辑:程序博客网 时间:2024/06/10 16:41


遇到问题:判断fast->next->next是否为空,需要先判断fast->next是否为空。

题目:

Given a singly linked list LL0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-2→…

You must do this in-place without altering the nodes' values.

For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.

////  main.cpp//  ReorderList////  Created by stongan on 4/29/15.//  Copyright (c) 2015 pang stongan. All rights reserved.//#include <iostream>using namespace std;//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 == NULL || head->next == NULL)            return;                ListNode* fast = head;        ListNode* slow = head;        //                while(fast != NULL){//                    cout <<"fast:" <<fast->val <<endl;//                    fast = fast->next;//                }//                while(slow != NULL){//                    cout <<"slow:" <<slow->val <<endl;//                    slow = slow->next;//                }        //与判断fast->next->next是否为空,需要先判断fast->next是否为空        while(fast->next != NULL && fast->next->next != NULL){            fast = fast->next->next;            slow = slow->next;        }                fast = slow;        slow = slow->next;        fast->next = NULL;                ListNode* pre = slow;        slow = slow->next;        pre->next = NULL;        while(slow != NULL){            ListNode* next = slow->next;            slow->next = pre;            pre = slow;            slow = next;        }                    ListNode* cur = head;        while(cur != NULL && pre!=NULL){            ListNode* next1 = cur->next;            ListNode* next2 = pre->next;            cur->next = pre;            pre->next = next1;            cur = next1;            pre = next2;        }    }};int main(int argc, const char * argv[]) {    Solution sol;    ListNode* tmp = new ListNode(1);    ListNode* tmp2 = new ListNode(2);    ListNode* tmp3 = new ListNode(3);    //ListNode* tmp4 = new ListNode(4);    tmp->next = tmp2;    tmp2->next = tmp3;    //tmp3->next = tmp4;    sol.reorderList(tmp);    while(tmp!=NULL){        cout <<tmp->val <<endl;        tmp = tmp->next;    }    return 0;}


0 0