本文主要是介绍【PAT】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.
翻译:给一个常量K和一个单链表L,你需要将每K个L上的元素倒置。举个例子,如果给定的L为 1→2→3→4→5→6,如果K为3,则你必须输出 3→2→1→6→5→4; 如果K为4,则你必须输出4→3→2→1→5→6。
INPUT FORMAT
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.
翻译:每个输入文件包含一组测试数据。对于每组输入数据,第一行包括头结点的地址,一个正整数N(<=10^5),代表总节点数,和一个正整数K(<=N),代表节点总数,和一个正整数K(<=N),代表需要转置的长度K。节点的地址为一个5位非负整数,-1代表NULL。
OUTPUT FORMAT
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
解题思路
先搜索一遍链表,将节点按照原链表顺序添加到vector中,再根据题目描述,如果vector长度大于等于K,则倒序将前K个压入结果vector中,并将前K个节点删除,小于K时就正序压入。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
#include<vector>
#include<algorithm>
#define INF 99999999
using namespace std;
struct node{int id,key;node(){}node(int ID,int k):id(ID),key(k){}
}d[100010];
vector<node> v;
vector<node> ans;
int S,N,K;
int main(){scanf("%d%d%d",&S,&N,&K);int id1,key,id2;for(int i=0;i<N;i++){scanf("%d%d%d",&id1,&key,&id2);d[id1].id=id2;d[id1].key=key; }while(S!=-1){v.push_back(node(S,d[S].key));S=d[S].id;}while(v.size()>=K){for(int i=K-1;i>=0;i--){ans.push_back(v[i]);}v.erase(v.begin(),v.begin()+K);}for(int i=0;i<v.size();i++){ans.push_back(v[i]);} for(int i=0;i<ans.size();i++){if(i==ans.size()-1)printf("%05d %d -1\n",ans[i].id,ans[i].key);else printf("%05d %d %05d\n",ans[i].id,ans[i].key,ans[i+1].id);}return 0;
}
这篇关于【PAT】1074. Reversing Linked List (25)【链表的使用】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!