【Leetcode】Reorder List


遇到问题:判断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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值