标签:
#include <iostream> using namespace std; struct Node{ int data; Node* next; }; Node* makeLinkedList(int n) { Node* allNode = new Node[n]; for(int i = 0; i < n; i++) { allNode[i].next = &allNode[i+1]; allNode[i].data = i + 1; if (i == n - 1) { allNode[n-1].next = NULL; } } return &allNode[0]; } void printLinkedList(Node* head) { while(head){ cout << head->data << endl; head = head->next; } } Node* reverse(Node* head) { Node* newhead = NULL; Node* left = head; while(left) { if (!newhead) { newhead = left; left = left->next; newhead->next = NULL; continue; } Node* top = left; left = left->next; top->next = newhead; newhead = top; } return newhead; } Node* reverseByNStep(Node* head, int n) { Node *unreversed = NULL; Node *reversing = NULL; Node *reversingTail = NULL; Node *reversed = NULL; Node* ret = NULL; // place all to unreversed unreversed = head; while(unreversed) { // split unreversed to two parts - reversing and unreversed reversing = unreversed; reversingTail = NULL; for(int i = 0; i < n; i++) { if(!unreversed) break; else reversingTail = unreversed; // shrink the unreversed unreversed = unreversed->next; } if (reversingTail) reversingTail->next = NULL; // reverse the reversing segment // and get the reversed segment‘s head and tail Node* segTail = reversing; Node* segHead = reverse(reversing); // the first reversed segment should save the returned head if (!reversed) { ret = segHead; } else { // for second+ segments // join the reversed part with segment head reversed->next = segHead; } // join the segment tail with the unreversed part segTail->next = unreversed; // expand the reversed part reversed = segTail; } // return final result return ret; } int main() { Node* head = makeLinkedList(10); printLinkedList(head); Node* r = reverseByNStep(head, 5); printLinkedList(r); }
标签:
原文地址:http://my.oschina.net/u/1179554/blog/374952