2.2.9—单链表—Reverse Nodes in k-Group

来源:互联网 发布:魔兽争霸3全屏软件 编辑:程序博客网 时间:2024/05/22 04:46
描述
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
If the number of nodes is not a multiple of k then le-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example, Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5

#include<iostream>using namespace std;struct node{int data;node *next;};class mylist{node *head;public:mylist(){head = new node();head->next = NULL;}void CreateList(int a[], int n);void Display();friend void Reverse(mylist &list, int begin, int end);//逆置begin和end之间的数friend void ReverseNodesinKGroup(mylist &list, int k);//调用Revserse()函数~mylist();};void mylist::CreateList(int a[], int n){node *p = head;for (int i = 0; i < n; i++){node *q = new node();q->data = a[i];p->next = q;p = q;}p->next = NULL;}void mylist::Display(){node *p = head->next;while (p){cout << p->data << " ";p = p->next;}cout << endl;}void Reverse(mylist &list, int begin, int end){//处理begin=1的情况if (begin == 1){node *pbegin = list.head->next;node *pend = pbegin;for (int i = 1; i <= end - begin; i++)pend = pend->next;for (int i = begin; i < end; i++){list.head->next = pbegin->next;pbegin->next = pend->next;pend->next = pbegin;pbegin = list.head->next;}return;}//处理begin!=1的情况node *pbegin = list.head->next;node *prebegin = NULL;for (int i = 1; i < begin; i++){prebegin = pbegin;pbegin = pbegin->next;}node *pend = pbegin;for (int i = 1; i <= end - begin; i++)pend = pend->next;for (int i = begin; i < end; i++){prebegin->next = pbegin->next;pbegin->next = pend->next;pend->next = pbegin;pbegin = prebegin->next;}}void ReverseNodesinKGroup(mylist &list, int k){node *p = list.head->next;int length = 0;while (p){length++;p = p->next;}int group = length / k;for (int i = 0; i < group; i++){Reverse(list, i*k + 1, (i + 1)*k);}}mylist::~mylist(){node *p = head;while (head){head = p->next;delete p;p = head;}}int main(){//===const int n = 7;int a[n] = { 1, 2, 3, 4, 5, 6, 7 };mylist list;list.CreateList(a, n);list.Display();//===int k = 2;ReverseNodesinKGroup(list, k);list.Display();}