1025 反转链表
来源:互联网 发布:怎么破解红蜘蛛软件 编辑:程序博客网 时间:2024/05/16 06:28
题目信息:
给定一个常数K以及一个单链表L,请编写程序将L中每K个结点反转。例如:给定L为1→2→3→4→5→6,K为3,则输出应该为3→2→1→6→5→4;如果K为4,则输出应该为4→3→2→1→5→6,即最后不到K个元素不反转。
输入格式:
每个输入包含1个测试用例。每个测试用例第1行给出第1个结点的地址、结点总个数正整数N(<= 105)、以及正整数K(<=N),即要求反转的子链结点的个数。结点的地址是5位非负整数,NULL地址用-1表示。
接下来有N行,每行格式为:
Address Data Next
其中Address是结点地址,Data是该结点保存的整数数据,Next是下一结点的地址。
输出格式:
对每个测试用例,顺序输出反转后的链表,其上每个结点占一行,格式与输入相同。
输入样例:00100 6 400000 4 9999900100 1 1230968237 6 -133218 3 0000099999 5 6823712309 2 33218输出样例:
00000 4 3321833218 3 1230912309 2 0010000100 1 9999999999 5 6823768237 6 -1
代码:
#include <iostream>#include <algorithm>#include <cmath>#include <cstdio>#include <cstring>#include <cctype>using namespace std;struct node{int data;int next; }node[100000];int firstAdd, N, K;void solve(){int add[N], n = 0;add[n ++] = firstAdd;while(n < N){add[n] = node[add[n - 1]].next;n ++;if(add[n - 1] == -1)break;}for(int i = 0; i + K - 1 < n; i += K){node[add[i]].next = node[add[i + K - 1]].next;for(int j = i + 1; j < i + K; j ++){node[add[j]].next = add[j - 1];}if(i - 1 >= 0)node[add[i - 1]].next = add[i + K - 1];for(int x = 0; x*2 < K; x ++){swap(add[i + x], add[i + (K - 1 - x)]);}}for(int a = add[0]; a != -1; a = node[a].next){printf("%05d %d ", a, node[a].data);if(node[a].next == -1)printf("-1\n");elseprintf("%05d\n", node[a].next);}}int main(){cin >> firstAdd >> N >> K;for(int i = 0; i < N; i ++){int add;cin >> add;cin >> node[add].data >> node[add].next;} solve();return 0;}
我的思路是,把地址为address的节点存在结构体数组node[address]里,所不同的是这里的指针存的是node的下标,然后模拟链表翻转
注意:最后一个测试点存在 不在链表上的点,要去掉。
0 0
- 1025 反转链表
- 1025 反转链表
- 1025 反转链表
- 1025 反转链表
- pat 1025 反转链表
- PAT 1025 反转链表
- PAT 1025反转链表
- PAT 1025反转链表
- ZJU PAT 1025 反转链表
- 1025_反转链表 (25)
- 反转链表 (PAT-B-1025)
- PAT_乙级 1025 反转链表
- PAT 乙等 1025 反转链表
- PAT 乙级-1025 链表反转
- 链表反转
- 反转链表
- 单向链表反转
- 链表反转:
- 89. Gray Code
- WebService学习总结(四)——调用第三方提供的webService服务
- Eclipse使用问题
- 264.leetcode Ugly Number II(medium)[寻找第N个丑数]
- 377. Combination Sum IV-动态规划
- 1025 反转链表
- Spring与Hibernate集成中的Session问题
- cookie
- ssh环境搭建
- 上台阶问题(递归)
- Mybatis源码导入eclipse
- C++和java异常处理中关于finally的区别
- MYSQL SELECT INTO临时表
- 直接NEW线程请求简单网络数据的实例