L2-022. 重排链表
时间限制
500 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
陈越
给定一个单链表 L1→L2→...→Ln-1→Ln,请编写程序将链表重新排列为 Ln→L1→Ln-1→L2→...。例如:给定L为1→2→3→4→5→6,则输出应该为6→1→5→2→4→3。
输入格式:
每个输入包含1个测试用例。每个测试用例第1行给出第1个结点的地址和结点总个数,即正整数N (<= 105)。结点的地址是5位非负整数,NULL地址用-1表示。
接下来有N行,每行格式为:
Address Data Next
其中Address是结点地址;Data是该结点保存的数据,为不超过105的正整数;Next是下一结点的地址。题目保证给出的链表上至少有两个结点。
输出格式:
对每个测试用例,顺序输出重排后的结果链表,其上每个结点占一行,格式与输入相同。
输入样例:00100 6 00000 4 99999 00100 1 12309 68237 6 -1 33218 3 00000 99999 5 68237 12309 2 33218输出样例:
68237 6 00100 00100 1 99999 99999 5 12309 12309 2 00000 00000 4 33218 33218 3 -1
// 这个题目我觉得必须要用一维数组存储,因为数据给出时不是按照链表实际顺序给出的,如果按真实链表存储,那么在数据输入时会出现遍历链表的情况,时间复杂度会提高,可能会超时。 // 由于需要倒序输出,所以每个结点需要得到他的前一个节点地址,故加入pre存储地址。 // 每个节点前一个节点的地址需要通过遍历链表来处理。 // 输出时注意区分节点是奇数个还是偶数个来分别输出。 #include <iostream> #include <vector> using namespace std; struct Node { int pre; int data; int next; }; vector<Node> list(100001); // 获取前一个节点的地址 void deal_with(int start) { while (list[start].next != -1) { list[list[start].next].pre = start; start = list[start].next; } } int main() { //freopen("data.txt", "r", stdin); int start, N, end; cin >> start >> N; // 读取数据 for (int i = 0; i < N; i++) { Node n; int address; cin >> address >> n.data >> n.next; list[address] = n; if (n.next == -1) end = address; } deal_with(start); // 分别输出 if (N % 2 == 0) while (1) { if (list[end].next == start) return 0; else { printf("%05d %d %05d\n", end, list[end].data, start); end = list[end].pre; } if (start == end) { printf("%05d %d -1\n", start, list[start].data); return 0; } else { printf("%05d %d %05d\n", start, list[start].data, end); start = list[start].next; } } else while (1) { if (list[end].next == start) return 0; else if (end == start) { printf("%05d %d -1\n", end, list[end].data); return 0; } else { printf("%05d %d %05d\n", end, list[end].data, start); end = list[end].pre; } printf("%05d %d %05d\n", start, list[start].data, end); start = list[start].next; } return 0; }
622

被折叠的 条评论
为什么被折叠?



