1074 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 (≤105) 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
题目要求:
链表每k个节点进行翻转,若不足k个节点,则不翻转
思路:
1. 利用hash的方法,data[i]表示地址为i的结点数据,next[i]表示地址i的结点的下一个结点的地址。
2. 由于输入中可能存在无效结点,因此需要统计有效结点,将有效结点按照顺序记录在数组list中,同时设置一个result数组,初始时让result与list相等。
3. 一共需要翻转n/k组,每一组的起始结点为i*k,末尾结点为(i+1)*k-1 输出时注意最后一行数据特殊输出
#include<iostream>
using namespace std;
int datan[100005], nextn[100005], list[100005], result[100005];
//这里不使用data和next做数组名是因为会出错,提示意义不明
//可能与关键字符重复
int main()
{
int first, n, k;
cin >> first >> n >> k;
int temp,sum=0;
for (int i = 0; i < n; i++) //输入数据及下一个节点地址
{
cin >> temp;
cin >> datan[temp] >> nextn[temp];
}
while (first != -1) // 可能输入了无效节点,这里把有效节点按顺序排列在list中
{
list[sum] = first;
result[sum] = first; //result为最后节点排序,先让其与list相等
first = nextn[first];
sum++;
}
for (int i = 0; i < sum / k; i++) // 共有sum/k组数据需逆序
{
for (int j = 0; j < k; j++) //第i组数据的初始序号为i*k,末尾序号为(i+1)*k-1
result[i*k+j] = list[(i + 1) * k - 1 -j];
}
for (int i = 0; i < sum; i++)
{
if (i < sum - 1) //最后一组特殊输出
printf("%05d %d %05d\n", result[i], datan[result[i]], result[i + 1]);
else printf("%05d %d -1\n", result[i], datan[result[i]]);
}
}
注:算法笔记上的代码不如柳神代码简洁。