【MOOC】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 (≤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

这道题之前做过,乙级里有,当时不会做,参考写的,学到了,这次一看到这个题就有了思路,只希望不是定式思维就好,第一次提交就过了两个测试点,4分。。第二次才满分,原因在于最后的输出那里,应该是v[i+1],我给弄成了v[i]的next,就错了,有的结点不一定在链表上,这是这个题的一个坑,之前做就觉得很坑,唉这次还是被坑了,所以需要记录有效的个数,这里由于采用的vector,直接用它的大小记录就可以,不用计数器。下边这个链接题的做法和这个的思路一样,可以对比着写

1-10 链表去重 (20分)(两遍过)

#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;
} 

猜你喜欢

转载自blog.csdn.net/weixin_45845039/article/details/108720440