以K大小为一组反转单链表

28 篇文章 0 订阅

例如

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/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值