例如
Example:
Inputs: 1->2->3->4->5->6->7->8->NULL and k = 3
Output: 3->2->1->6->5->4->8->7->NULL.
Inputs: 1->2->3->4->5->6->7->8->NULL and k = 5
Output: 5->4->3->2->1->8->7->6->NULL.
我们可以把整个链表分成多个长度为 k 的子链表, 然后,我们再反转每一个子链表(递归)。问题的关键是我们需要把每个子链表再连接起来。所以,对每一个子链表操作以后,我们需要返回该子链表的头(head),然后,我们设置前一个子链表的最后一个node,把它的next 指向下一个链表返回的头(head),这样,所有的子链表就连接起来了。
源码如下:
//#param warning(disable:4996)
#define _CRT_SECURE_NO_DEPRECATE
#include<iostream>
#include<malloc.h>
using namespace std;
/*将单链表以k个为一组反转*/
typedef struct Node {
int data;
struct Node * next;
}Node;
void printList(Node *&list) {
Node *p = list->next;
while (p != NULL) {
cout << p->data << " ";
p = p->next;
}
cout<<endl;
}
Node* createListNode1() {
Node * list = (Node*)malloc(sizeof(Node));//头结点
list->next = NULL;
int num[] = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 };
int len = sizeof(num) / sizeof(int);
while (len > 0) {
Node * node = (Node*)malloc(sizeof(Node));
node->data = num[len - 1];
node->next = list->next;
list->next = node;
len--;
}
return list;//返回头结点值
}
Node* createListNode2() {
Node * list = (Node*)malloc(sizeof(Node));//头结点
list->next = NULL;
int num[] = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 };
int len = sizeof(num) / sizeof(int);
int i = 0;
Node *temp= list;
while (len > 0) {
Node * node = (Node*)malloc(sizeof(Node));
node->data = num[i];
temp->next = node;
temp = node;
len--;
i++;
}
temp->next = NULL;//将最后一个节点后序节点置空否。
return list;//返回头结点值
}
Node* rollback(Node *&head, int k) {
Node *pre = NULL;
Node *next = NULL;
Node *curr = head;
int count = 0;
while (curr != NULL&&count<k) {
next = curr->next;
curr->next = pre;
pre = curr;
curr = next;
count++;
}
if (curr != NULL) {
head->next = rollback(next, k);
}
return pre;
}
int main()
{
Node *list = createListNode2();
cout << "创建的链表为:" << endl;
printList(list);
list->next = rollback(list->next, 4);//因为使用递归所以从首节点开始传递
cout << "调整后的链表为:" << endl;
printList(list);
system("PAUSE");
return 0;
}
算法思想参考:http://www.geeksforgeeks.org/reverse-a-list-in-groups-of-given-size/