Given a singly linked list L1→L2→⋯→Ln−1→Ln, please write a program to rearrange the linked list as Ln→L1→Ln−1→L2→⋯. For example: Given that L is 1→2→3→4→5→6, the output should be 6→1→5→2→4→3.
Input format:
Each input contains 1 test case. The first line of each test case gives the address of the first node and the total number of nodes, that is, positive integer N (≤105). The address of the node is a 5-bit non-negative integer, and the NULL address is represented by −1.
Next there are N lines, each line format is:
Address Data Next
Among them Address
is the node address; Data
it is the data saved by the node, which is a positive integer not exceeding 105; Next
it is the address of the next node. The topic guarantees that there are at least two nodes on the given linked list.
Output format:
For each test case, sequentially output the rearranged result linked list, each node on it occupies one line, and the format is the same as the input.
Input sample:
00100 6
00000 4 99999
00100 1 12309
68237 6 -1
33218 3 00000
99999 5 68237
12309 2 33218
Sample output:
68237 6 00100
00100 1 99999
99999 5 12309
12309 2 00000
00000 4 33218
33218 3 -1
Problem-solving ideas:
The simulation process is enough, but it should be noted that the node given in the title may not be in this linked list, so a counter cnt is needed to count the length of this linked list to re-correct the value of n.
Code example:
#include <bits/stdc++.h>
using namespace std;
struct stu
{
int data; //数据
int next; //后继节点
int pre; //前驱节点
}res[100020];
vector<int> ans; //存已经重排好的节点的地址
int main()
{
int first_ip, n;
cin >> first_ip >> n;
for(int i = 0; i < n; i++)
{
int ip;
cin >> ip;
cin >> res[ip].data >> res[ip].next;
}
int cnt = 0; //计数器 数链表的长度
int p = first_ip;
int q = -1;
//本循环的作用是形成前驱节点和计算链表的真正长度
while(p != -1)
{
res[p].pre = q;
q = p;
p = res[p].next;
cnt++;
}
n = cnt; //修正n的值
p = first_ip;
while(q != -1 && p != -1)
{
ans.emplace_back(q);
ans.emplace_back(p);
q = res[q].pre;
p = res[p].next;
}
for(int i = 0; i < n - 1; i++)
{
printf("%05d %d %05d\n", ans[i], res[ans[i]].data, ans[i + 1]);
}
printf("%05d %d -1\n", ans[n - 1], res[ans[n - 1]].data);
return 0;
}
operation result: