02-线性结构3 Reversing Linked List (25分)
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
解题思路:
1、程序框架:
- 读入数据
- 逆转数据
- 打印
2、读入数据:本题使用了姥姥的抽象链表的解法,即构造结构体变量,分别保存数据以及下一个节点的位置,并利用结构体创建足够空间的数组,因为数组的下标即为数据存放的位置,因此我在创建结构体变量时没有创建一个储存位置的变量。
3、逆转数据: - 正常情况(不考虑输入的链表有多余结点):
①每次对k个结点进行逆序,逆序后,将逆序部分的尾结点指向下一个可能需要逆序的头
②判断下一个待逆序部分是否满足长度要求,若不满足,则直接退出,若满足,则将逆序部分的尾结点指向下一个逆序部分的头结点。
③重复①②,直至不满足长度要求为止 - 非正常情况(输入的链表有多余结点):
与正常情况相比,除②之外,其余部分相同,由于可能存在无效的结点,因此和正常情况相比,需要判断有效结点的个数是否满足长度要求(貌似是可以直接改变②的判断条件来直接实现两种情况的要求)。
4、打印数据:因为需要与输入格式一致,所以使用printf注意加上控制符。
AC代码如下:
#include <stdio.h>
#define Maxsize 100000
struct LinkList {
int data;
int next;
};
void Read (struct LinkList L[]);
int Reverse (struct LinkList L[], int k, int head);
void Print (int first, struct LinkList L[