PAT 1074
链接:http://www.patest.cn/contests/pat-a-practise/1074
反转链表,但是PAT上的链表题(其实总共也就两道题)都是可以使诈的,比如list sorting,拿到了数据之后,记录好所有node的val和cur_address,排个序然后再依次打出来就好了... 比起用归并写简单太多也不容易错太多
这道题也是用使诈的方法更不容易错,记录下来每一个节点的值,然后再用栈和vector将结果拿到,注意当n % k == 0时候的情况。
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
#include <stack>
using namespace std;
//#define OJ
#ifdef OJ
#define fin cin
#else
ifstream fin("in.txt");
#endif
struct Node{
int cur_address;
int val;
int next_address;
};
int main(){
string start;
int n, k;
fin >> start >> n >> k;
vector<Node> nodes(100000);
for (int i = 0; i < n; i++){
Node tmp;
string s1, s2;
fin >> s1 >> tmp.val >> s2;
tmp.cur_address = atoi(s1.c_str());
tmp.next_address = atoi(s2.c_str());
nodes[tmp.cur_address] = tmp;
}
int start_idx = atoi(start.c_str());
int cur_address = start_idx;
vector<int> path;
while (start_idx != -1){
path.push_back(start_idx);
start_idx = nodes[start_idx].next_address;
}
vector<int> res;
int idx = 0;
n = path.size();
for (; idx + k - 1 < n; idx += k){
stack<int> node_stack;
for (int i = 0; i < k; i++){
node_stack.push(path[idx + i]);
}
while (!node_stack.empty()){
int tmp = node_stack.top();
res.push_back(tmp);
node_stack.pop();
}
}
for (; idx < n; idx++){
res.push_back(path[idx]);
}
for (int i = 0; i < n - 1; i++){
printf("%05d %d %05d\n", nodes[res[i]].cur_address, nodes[res[i]].val, nodes[res[i + 1]].cur_address);
}
printf("%05d %d %d\n", nodes[res[n - 1]].cur_address, nodes[res[n - 1]].val, -1);
return 0;
}

浙公网安备 33010602011771号