1025 反转链表 (25 分)(c语言)

给定一个常数 K 以及一个单链表 L,请编写程序将 L 中每 K 个结点反转。例如:给定 L 为 1→2→3→4→5→6,K 为 3,则输出应该为 3→2→1→6→5→4;如果 K 为 4,则输出应该为 4→3→2→1→5→6,即最后不到 K 个元素不反转。

输入格式:

每个输入包含 1 个测试用例。每个测试用例第 1 行给出第 1 个结点的地址、结点总个数正整数 N (≤105)、以及正整数 K (≤N),即要求反转的子链结点的个数。结点的地址是 5 位非负整数,NULL 地址用 −1 表示。

接下来有 N 行,每行格式为:

Address Data Next

其中 Address 是结点地址,Data 是该结点保存的整数数据,Next 是下一结点的地址。

输出格式:

对每个测试用例,顺序输出反转后的链表,其上每个结点占一行,格式与输入相同。

输入样例:

00100 6 4
00000 4 99999
00100 1 12309
68237 6 -1
33218 3 00000
99999 5 68237
12309 2 33218

结尾无空行

输出样例:

00000 4 33218
33218 3 12309
12309 2 00100
00100 1 99999
99999 5 68237
68237 6 -1

结尾无空行

#include<stdio.h>
#pragma warning(disable:4996)
typedef struct a {
	int address;
	int data;
	int next;
}lianbiao;
lianbiao orgin[100000], sort[100000];
void nixu(lianbiao arr[], int begin, int end);
int main() {
	int adr, N, K;
	scanf("%d%d%d", &adr, &N, &K);
	for (int cnt = 0; cnt < N; cnt++) {
		lianbiao temp;
		scanf("%d%d%d", &temp.address, &temp.data, &temp.next);
		orgin[temp.address] = temp;
	}
	for (int cnt = 0; cnt < N; cnt++) {
		sort[cnt] = orgin[adr];
		adr = sort[cnt].next;
		if (adr == -1) {
			N = cnt + 1;
			break;
		}
	}

	/*for (int cnt = 1; K * cnt < N; cnt++) {
		nixu(sort, K * (cnt - 1), K * cnt-1);
	}*/
	
	for (int cnt = 0;  cnt < N / K; cnt++) {
		for (int cnt1 = 0; cnt1 < K / 2; cnt1++) {
			lianbiao temp = sort[K * cnt + cnt1];
			sort[K * cnt + cnt1] = sort[K * cnt + K - 1 - cnt1];
			sort[K * cnt + K - 1 - cnt1] = temp;
		}
	}

	//for (int i = 0; i < N / K; i++) {//反转的次数 
	//	for (int j = 0; j < K / 2; j++) {//反转 
	//		lianbiao temp;
	//		temp = sort[j + i * K];
	//		sort[j + i * K] = sort[K - 1 - j + i * K];//数组下标确认好 
	//		sort[K - 1 - j + i * K] = temp;
	//	}
	//}

	for (int cnt = 0; cnt < N; cnt++) {
		if (cnt + 1 < N) {
			sort[cnt].next = sort[cnt + 1].address;
			printf("%05d %d %05d\n", sort[cnt].address, sort[cnt].data, sort[cnt].next);
		}
		else {
			sort[cnt].next = -1;
			printf("%05d %d %-d", sort[cnt].address, sort[cnt].data, sort[cnt].next);
		}
	}
	return 0;
}
void nixu(lianbiao arr[], int begin, int end) {
	if (begin >= end) return;
	lianbiao temp = arr[begin];
	arr[begin] = arr[end];
	arr[end] = temp;
	nixu(arr, begin+1, end-1);
}

我踩过的坑:

1.这道题逆序不能用递归,我也不知道为什么,我用我原来写的递归函数进行逆序,通不过2,3测试点

2.循环过程中cnt<N/K和K*cnt<N是有区别的,例如当N=5,K=3.两者的循环次数是不一样的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cjz-lxg

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值