首页 > 代码库 > 链表逆序(每N个一组)
链表逆序(每N个一组)
#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); }
链表逆序(每N个一组)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。