PAT-A 1074,题目地址:https://www.patest.cn/contests/pat-a-practise/1074
这道题目本身比较简单,但是有一个坑点,就是并非所有的节点都在链表中,可能存在悬空的节点。因此首先应该将链表排序,找出链表中的所有节点,忽略其他节点。没有注意到这一点,最后一个case会报段错误。
代码
#include <iostream>
#include <vector>
#include <map>
#include <string>
using namespace std;
struct Node{
string address;
int data;
string next;
Node(): address(""), data(0), next(""){}
Node(const Node &a): address(a.address), data(a.data), next(a.next){}
};
bool cmp(const Node &a, const Node &b){
return a.address < b.address;
}
int main(){
int n, k;
string head;
cin >> head >> n >> k;
Node node;
map<string, Node> m;
for(int i = 0; i < n; i++){
cin >> node.address >> node.data >> node.next;
m[node.address] = Node(node);
}
vector<Node> nodes;
string next = head;
while(next != string("-1")){
map<string, Node>::iterator iter = m.find(next);
nodes.push_back(iter->second);
next = iter->second.next;
}
int count = nodes.size() / k; //注意此处的nodes.size() == n并不一定成立
for(int j = 1; j <= count; j++){ //要反转几组
string rest = nodes[j * k - 1].next;
for(int i = j * k - 1; i >= (j-1) * k; i--){
if(i == j * k - 1 && j != 1){ //上一组的尾节点应该指向这一组的头结点
nodes[(j-2) * k].next = nodes[i].address;
}
if(i != (j-1) * k){
nodes[i].next = nodes[i-1].address;
}
else{
nodes[i].next = rest;
}
}
}
for(int j = 1; j <= count; j++){
for(int i = j * k - 1; i >= (j-1) * k; i--){
printf("%s %d %s\n", nodes[i].address.c_str(), nodes[i].data, nodes[i].next.c_str());
}
}
for(int i = count * k; i < nodes.size(); i++){
printf("%s %d %s\n", nodes[i].address.c_str(), nodes[i].data, nodes[i].next.c_str());
}
return 0;
}