Algorithm/c/反转链表/计算机171曹哲奇.c

112 lines
2.5 KiB
C
Executable File
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*1025 反转链表 25 分)
给定一个常数 K 以及一个单链表 L请编写程序将 L 中每 K 个结点反转。例如:给定 L 为 1→2→3→4→5→6K 为 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
*/
//#pragma warning(disable:4996)
#include<stdio.h>
#include<stdlib.h>
typedef struct LinkList
{
int Address;
int Data;
int Next;
}linklist;
int main()
{
linklist list[100000], *p1, *p2;
int h_address, num, r_num, p_address, n_address, cnt = 0, tmp;
p1 = (linklist*)malloc(sizeof(struct LinkList));
p2 = (linklist*)malloc(sizeof(struct LinkList));
scanf("%d %d %d", &h_address, &num, &r_num);
getchar();
for (int i = 0; i < num; i++)
{
int address, data, next;
scanf("%d %d %d", &address, &data, &next);
getchar();
list[address].Address = address;
list[address].Data = data;
list[address].Next = next;
}
p1 = &list[h_address];
for (;;)
{
cnt++;
if (p1->Next == -1)
break;
p1 = &list[p1->Next];
}
tmp = h_address;
while (cnt >= r_num)
{
p1 = &list[tmp];
p_address = tmp;
n_address = p1->Next;
for (int i = 0; i < r_num; i++)
{
if (i)
{
n_address = p1->Next;
p1->Next = p_address;
p_address = p1->Address;
}
p1 = &list[n_address];
}
if (p2 != NULL)
p2->Next = p_address;
if (!i)
h_address = p_address;
list[tmp].Next = n_address;
p2 = &list[tmp];
tmp = p1->Address;
cnt -= r_num;
i++;
}
p1 = &list[h_address];
for (;;)
{
if (p1->Next >= 0)
printf("%05d %d %05d\n", p1->Address, p1->Data, p1->Next);
else
printf("%05d %d %d\n", p1->Address, p1->Data, p1->Next);
if (p1->Next == -1)
break;
p1 = &list[p1->Next];
}
return 0;
}