L2-022. 重排链表(变型)
来源:互联网 发布:java贪吃蛇游戏源代码 编辑:程序博客网 时间:2024/05/24 06:03
本题要求:
给定一个单链表 L1→L2→…→Ln-1→Ln,请编写程序将链表重新排列为 Ln→L1→Ln-2→L3→…。例如:给定L为1→2→3→4→5→6,则输出应该为6→1→4→3→2→5。
输入格式:
每个输入包含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 00000
00000 4 33218
33218 3 12309
12309 2 99999
99999 5 -1
解题思路 :
先进行分组,再交叉插入即可。
代码 :
#include <iostream>#include <iomanip>using namespace std;class Node { public: int data; int next; Node() { data = 0; next = 0; }};Node map[100001];int main() { int head; int n; cin >> head >> n; for (int i = 0; i < n; i++) { int a, d, next; cin >> a >> d >> next; map[a].data = d; map[a].next = next; } int m = 1; int now = head; int temp; int last = -1; while (now != -1) { temp = map[now].next; if (m % 2 == 0) { map[now].next = last; last = now; } else { if (temp == -1) { map[now].next = -1; } else { map[now].next = map[temp].next; } } m++; now = temp; } now = head; head = last; int tempLast, tempNow; while (now != -1 && last != -1) { tempLast = map[last].next; map[last].next = now; tempNow = map[now].next; map[now].next = tempLast; last = tempLast; now = tempNow; } now = head; while (now != -1) { cout << setfill('0') << setw(5) << now << " " << map[now].data << " "; if (map[now].next != -1) { cout << setw(5) << map[now].next << endl; } else { cout << -1 << endl; } now = map[now].next; } return 0; }
0 0
- L2-022. 重排链表(变型)
- L2-022. 重排链表
- L2-022. 重排链表
- L2-022. 重排链表
- L2-022. 重排链表
- L2-022. 重排链表
- PAT L2-022 重排链表 (deque双向队列)
- 团体程序设计天梯赛-练习集 -- L2-022. 重排链表
- 团体程序设计天梯赛L2-022 重排链表
- 链表的交错重排L1,Ln,L2,Ln-1 ....
- 2017年团体程序设计天梯赛-总决赛 L2-2. 重排链表
- LintCode(99) 重排链表
- 重排链表
- 重排链表
- 重排链表
- 重排链表
- LintCode:重排链表
- LintCode : 重排链表
- 工作流-流程部署
- mAP在计算机视觉中的应用
- Java获取硬盘,CPU等信息
- 这几个问题答不对,就别说精通TCP
- js 复制文本的四种方式
- L2-022. 重排链表(变型)
- android中在线程中随时更新UI控件的值
- PHP排序算法系列:直接选择排序
- opencv函数解析目录
- 编程规约
- 制作ota差分包
- mysql中让数据库中的数据量翻倍
- Ubuntu14安装mysql并开启远程访问
- verilog 编写代码的顺序问题