PAT(Advanced) 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.
Input Specification:
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.
Output Specification:
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.
解答:
該題可以用vector來模擬連結串列的實現,然後每k個一組儲存在新的vector變數result中,最後輸出結果。剛開始如果過於專注於節點順序,會把題目搞複雜,要有大局觀。
AC程式碼如下:
#include<iostream>
#include<vector>
#include<algorithm>
#define maxn 1000000
using namespace std;
typedef struct{
int data, nxt;
}node;
typedef struct{
int addr, data;
}node2;
vector<node> vec(maxn);
int main()
{
int addr, n, k;
cin >> addr >> n >> k;
for(int i = 0; i < n; ++i)
{
int cur, d, nxt;
scanf("%d %d %d", &cur, &d, &nxt);
vec[cur].data = d;
vec[cur].nxt = nxt;
}
vector<node2> list;
for(int i = addr; i != -1; i = vec[i].nxt)
{
node2 tmp;
tmp.addr = i; tmp.data = vec[i].data;
list.push_back(tmp);
}
vector<node2> result;
int i;
for(i = 0; i + k <= list.size(); i += k)
{
int m = i, n = i + k - 1;
while(n >= m)
{
result.push_back(list[n]);
n--;
}
}
while( i < list.size() )
{
result.push_back(list[i++]);
}
for(int i = 0; i < result.size(); ++i)
{
if(i != result.size() - 1) printf("%05d %d %05d\n", result[i].addr, result[i].data, result[i+1].addr);
else printf("%05d %d -1\n", result[i].addr, result[i].data);
}
return 0;
}