A linked list consists of a series of structures, which are not necessarily adjacent in memory. We assume that each structure contains an integer key
and a Next
pointer to the next structure. Now given a linked list, you are supposed to sort the structures according to their key values in increasing order.
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive and an address of the head node, where is the total number of nodes in memory and the address of a node is a 5-digit positive integer. NULL is represented by .
Then lines follow, each describes a node in the format:
Address Key Next
where Address
is the address of the node in memory, Key is an integer in , and Next is the address of the next node. It is guaranteed that all the keys are distinct and there is no cycle in the linked list starting from the head node.
Output Specification:
For each test case, the output format is the same as that of the input, where is the total number of nodes in the list and all the nodes must be sorted order.
Sample Input:
5 00001
11111 100 -1
00001 0 22222
33333 100000 11111
12345 -1 33333
22222 1000 12345
Sample Output:
5 12345
12345 -1 00001
00001 0 11111
11111 100 22222
22222 1000 33333
33333 100000 -1
using namespace std;
struct Node{
string address;
int key;
string next;
bool operator < (const Node &t) const{
return key < t.key;
}
};
int n;
unordered_map<string, Node> mp;
int main(){
char head[10];
scanf("%d%s", &n, head);
char address[10], next[10];
int key;
while(n--){
scanf("%s%d%s", address, &key, next);
mp[address] = {address, key, next};
}
vector<Node> vs;
for(string i = head; i != "-1"; i = mp[i].next) vs.push_back(mp[i]);
printf("%d ", vs.size());
if(vs.size() == 0) puts("-1");
else{
sort(vs.begin(), vs.end());
printf("%s\n", vs[0].address.c_str());
for(int i = 0; i < vs.size(); i++){
if(i + 1 == vs.size())
printf("%s %d -1\n", vs[i].address.c_str(), vs[i].key);
else
printf("%s %d %s\n", vs[i].address.c_str(), vs[i].key, vs[i+1].address.c_str());
}
}
return 0;
}