遇到问题:判断fast->next->next是否为空,需要先判断fast->next是否为空。
题目:
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-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;
}