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}
.
下面是代码。要注意的是:1)第24和25行,fast pointer被初始化成slow pointer的下一个。(自己在纸上画一下,这样初始化的结果是什么)。不能把fast pointer 和slow pointer都初始化成head节点。
#include<iostream> #include<stdio.h> #include<stdlib.h> using namespace std; #include <string.h> #include <stack> #include <stdio.h> #include <stdlib.h> struct ListNode { int data; ListNode *next; ListNode(int x, ListNode* nex) : data(x), next(nex) {} }; ListNode* reverseList(ListNode* head); void printLL(ListNode* head); void reorderList(ListNode *head) { if(head==NULL || head->next == NULL || head->next->next==NULL) return; ListNode* slow = head; ListNode* fast = head->next; // fast should be the next of slow while(fast) { if(fast->next) fast = fast->next; else break; if(fast->next) fast = fast->next; else break; if(slow==NULL) slow = head; else slow = slow->next; } reverseList( slow->next ); slow->next = NULL; ListNode* cur1 = head; ListNode* cur2 = fast; while(cur1) { ListNode* nex1 = cur1->next; ListNode* nex2 = cur2->next; cur1->next = cur2; if(nex1 == NULL) { cur2->next = nex2; break; } else cur2->next = nex1; cur1 = nex1; cur2 = nex2; } } ListNode* reverseList(ListNode* head) // reverse a linked list { if(head==NULL) return head; if(head->next == NULL) return head; ListNode* tmp = reverseList(head->next); tmp->next = head; head->next = NULL; return head; } void printLL(ListNode* head) { while(head) { cout<<head->data<<" "; head = head->next; } } int main() { ListNode* n0 =new ListNode(0, NULL); ListNode* n1 =new ListNode(1, n0); ListNode* n2 =new ListNode(2, n1); ListNode* n3 =new ListNode(3, n2); ListNode* n4 =new ListNode(4, n3); ListNode* n5 =new ListNode(5, n4); ListNode* n6 =new ListNode(6, n5); ListNode* n7 =new ListNode(7, n6); reorderList(n7); printLL(n7); }