[MOOC] 02-Linear Structure 3 Reversing Linked List (25 points) (two passes)

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

I’ve done this question before, but it’s in Level B. I didn’t know how to do it at that time. I learned it by referring to what I wrote. This time I got an idea as soon as I saw this question. I just hope it’s not a fixed-style thinking. Two test points, 4 points. . The second time I got full marks. The reason is that the final output should be v[i+1]. I got the next of v[i] and it was wrong. Some nodes are not necessarily on the linked list. This is A pit in this question, I thought it was a pit when I did it before. Alas, it was still pitted this time, so we need to record the effective number. Here, because of the vector used, we can record it directly with its size instead of a counter. The practice of the link question below is the same as this idea, you can write in comparison

1-10 Removal of linked list (20 points) (two times)

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

typedef struct{
    
    
	int data;
	int next;
}Node;

Node node[100005];
vector<int> v;

int main(){
    
    
	ios::sync_with_stdio(false);
	int head,n,k;
	cin >> head >> n >> k;
	for(int i = 0;i<n;i++){
    
    
		int add;
		cin >> add;
		cin >> node[add].data >> node[add].next;
	}
	while(head!=-1){
    
    
		v.push_back(head);
		head = node[head].next;
	}
	int len = v.size();
	for(int i = 0;i<(len-len%k);i+=k){
    
    
		reverse(v.begin()+i,v.begin()+i+k);
	}
	for(int i = 0;i<len-1;i++){
    
    
		printf("%05d %d %05d\n",v[i],node[v[i]].data,v[i+1]);
	}
	printf("%05d %d -1\n",v[len-1],node[v[len-1]].data);
	return 0;
} 

Guess you like

Origin blog.csdn.net/weixin_45845039/article/details/108720440