02-线性结构3 Reversing Linked List (25分)

二次信任 提交于 2019-12-20 02:07:38

Given a constant K and a singly linked list L, you are supposed to reverse the links of every K elements on L. For example, given L being 1→2→3→4→5→6, if K=3, then you must output 3→2→1→6→5→4; if K=4, you must output 4→3→2→1→5→6.

Input Specification:
Each input file contains one test case. For each case, the first line contains the address of the first node, a positive N (≤10
​5
​​ ) which is the total number of nodes, and a positive K (≤N) which is the length of the sublist to be reversed. The address of a node is a 5-digit nonnegative integer, and NULL is represented by -1.

Then N lines follow, each describes a node in the format:

Address Data Next
where Address is the position of the node, Data is an integer, and Next is the position of the next node.

Output Specification:
For each case, output the resulting ordered linked list. Each node occupies a line, and is printed in the same format as in the input.

Sample Input:

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

Sample Output:

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

思路

这一题真的是折磨我太久了,每次都有点思路,但思路都不正确,不断的尝试,一次次的失败,负面情绪爆棚,最后还是看了姥姥的思路才把题目做对,负面情绪真的很影响自己,以后像这样想了两个半小时如果还没正确思路的话就不要做了,我得稳步提升,不能急不能慌,每天按照计划来就行,不会就是自己不行,再怎么郁闷也没用,还不如多花点时间在题目上,这也说明许多题目要练,许多难题要见,要不断的调整自己心态。

在这里插入图片描述
在这里插入图片描述

代码

#include <stdio.h>
struct LNode {
	int data;
	int next;
}T[100010];
int Revers(int frist, int k, int n);
int main()
{
	int frist, n, k, i, a, b, c;
	scanf("%d %d %d", &frist, &n, &k);
	T[100009].next = frist;
	for (i = 0; i < n; i++) {
		scanf("%d %d %d", &a, &b, &c);
		T[a].data = b;
		T[a].next= c;
	}
	frist = Revers(frist, k, n);
	while (frist != -1)
	{
		printf("%05d ", frist);
		printf("%d ", T[frist].data);
		if (T[frist].next != -1) {
			printf("%05d\n", T[frist].next);
		}
		else {
			printf("-1\n");
		}
		frist = T[frist].next;
	}
	return 0;
}
int Revers(int frist, int k, int n)
{
	int new, old, temp, cnt, f, c, head, flag = 1;
	head = 100009;//建一个头节点
	int number = -1;
	int tem = head;//number 和 tem 都是针对有多余节点设置的
	while (tem != -1) {
		tem = T[tem].next;
		number++; 
	}
	c = number / k;
	if (k <= number) {
		while (c) {
			cnt = 1;
			new = T[head].next;
			old = T[new].next;
			while (cnt < k) {
				temp = T[old].next;
				T[old].next = new;
				new = old;
				old = temp;
				cnt++;
			}
			T[T[head].next].next = old;
			temp = T[head].next;
			T[head].next = new;
			if (flag == 1) {
				f = new;
				flag = 0;
			}
			head = temp;
			c--;
		}
		return f;
	}
	else {
		return frist;
	}
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!