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

题目描述:有一条链表L,假设链表为1->2->3->4->5->6,现在要求你将链表分组为每k个数一组,每组的链表反转后串连在一起,最后输出。若k=3,则反转后的链表为3->2->1->6->5->4,若k=4,4->3->2->1->5->6,可以看到1、2、3、4这四个数可以分为1组,然后将其反序输出了,而5、6不足一组,则按顺序输出。


输入:第一行包括三个数,链表头节点Head,n表示链表节点数,k表示k个算组分为一组。接下来n行,包括每个结点的head结点、num、next结点

输出:将反转后链表的每个结点按顺序输出。


解题思路:题目输入的结点顺序不是正确,需要通过题目给定的head头节点先将链表串起来。在输入的时候,就可以将每个结点放入结构体数组中,使用每个结点的head作为索引,存放好后,可以通过给定的链表头节点Head,将链表串起来,放入l2结构体容器中。后面只需要将容器分组。为每组个数都小于等于k,然后进行反转,再存放到l3结构体容器中,最后输出。这就大功告成啦。

使用结构体数组来模拟链表,实现起来比较简单。


#include<bits/stdc++.h>
using namespace std;
struct node{
	int head, num, next;
};
const int maxn = 100005;
node l1[maxn];
vector<node> l2, l3;
int main()
{
	node t;
	int head, n, k;
	scanf("%d %d %d", &head, &n, &k);
	for(int i=0; i<n; i++){
		scanf("%d %d %d", &t.head, &t.num, &t.next);
		l1[t.head] = t;
	}
	while(head!=-1){
		t = l1[head];
		l2.push_back(t);
		head = t.next;
	}
	for(int i=0, j; i<l2.size(); i+=k){
		if(i+k<=l2.size()){
			j = i+k-1;
			while(j>=i){
				l3.push_back(l2[j]);
				j--;
			}
		}
		else{
			j = i;
			while(j<l2.size()){
				l3.push_back(l2[j]);
				j++;
			}
			break;
		}
	}
	for(int i=0; i<l3.size()-1; i++){
		printf("%05d %d %05d\n", l3[i].head, l3[i].num, l3[i+1].head);
	}
	printf("%05d %d -1\n", l3[l3.size()-1].head, l3[l3.size()-1].num);
	return 0;
}