PTA重排链表
一、题目描述
二、解题思路
利用map存储这个链表的顺序。前面那个string代表当前节点,映射的是一个结构体,里面存了下一个节点的信息,遍历一遍全部存入一个vector里面,然后从两边输出就行了。
三、代码实现
1 #include "bits/stdc++.h" 2 using namespace std; 3 struct node{ 4 string st1; 5 int id; 6 string nxt; 7 }; 8 map <string,node> mp; 9 vector <node> ans; 10 int main() 11 { 12 string st; 13 int n; 14 struct node temp1; 15 cin >> st >> n; 16 for(int i = 1;i <= n;i++){ 17 cin >> temp1.st1; 18 cin >> temp1.id; 19 cin >> temp1.nxt; 20 mp[temp1.st1] = temp1; 21 } 22 string end = "-1"; 23 while(st != end){ 24 ans.push_back(mp[st]); 25 st = mp[st].nxt; 26 } 27 int l,r; 28 l = 0,r = ans.size() - 1; 29 while(l <= r){ 30 if(l < r) 31 cout << ans[r].st1 << ' ' << ans[r].id << ' ' << ans[l].st1 << endl; 32 else if(l == r) 33 cout << ans[r].st1 << ' ' << ans[r].id << ' ' << -1 << endl; 34 r--; 35 if(l < r) 36 cout << ans[l].st1 << ' ' << ans[l].id << ' ' << ans[r].st1 << endl; 37 else if(l == r) 38 cout << ans[l].st1 << ' ' << ans[l].id << ' ' << -1 << endl; 39 l++; 40 } 41 return 0; 42 }
本文来自博客园,作者:{scanner},转载请注明原文链接:{https://home.cnblogs.com/u/scannerkk/}