《数据结构》02

编程入门 行业动态 更新时间:2024-10-24 18:26:15

《<a href=https://www.elefans.com/category/jswz/34/1769880.html style=数据结构》02"/>

《数据结构》02

题目

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 (≤10​ 5 ^5 5​​ ) 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.

Sample Input:

00100 6 4
00000 4 99999
00100 1 12309
68237 6 -1
33218 3 00000
99999 5 68237
12309 2 33218

Sample Output:

00000 4 33218
33218 3 12309
12309 2 00100
00100 1 99999
99999 5 68237
68237 6 -1

分析

题目大概意思就是给一组格式是Address data next的结点,按要求逆序输出
先观察,逆序后不变的地方是前两组数据,即每个结点的 Address 和 data 是不变的,继续观察,其实当前结点的 next 是下一个结点的 Address
我们考虑将 Address 和 data 存起来,还要体现它们的关系,可以用数组 Data[Address] = data,同样的,我们可以将 next 和 Address 也以这种形式存储,即 Next[Address] = next
这样存储的结果是,知道 Address 我们可以通过 Data[ ] 数组找到对应 data,可以通过 Next[ ] 数组找到对应的 next
这样存储后,我们再把整个链表“理顺”,给出的 first node 即为第一个 Address,Next[first node] 是下一个结点的 Address,再用一个数组 list[ ] 把每次遇到的 Address 记录下来
到此为止我们有了能根据 Address 找到其他数据的关系数组,也有顺序记录 Address 的数组,问题就从"反转链表"简化为了"反转 Address"
再以每 K 个结点为区间,反转 list[ ] 数组中存储的 Address,再根据 Address 和其他数据的关系,就能完整地输出链表了!

#include<stdio.h>
#include<iostream>
#define MaxSize 100005
using namespace std;
int main(){int Data[MaxSize];int Next[MaxSize];int list[MaxSize];int FirstAdd,N,K;scanf("%d %d %d",&FirstAdd,&N,&K);for(int i=0;i<N;i++){int tmpAdd,tmpData,tmpNext;scanf("%d %d %d",&tmpAdd,&tmpData,&tmpNext);Data[tmpAdd] = tmpData;Next[tmpAdd] = tmpNext;}int sum=0;   // 累计有效结点数 while(FirstAdd!=-1){   // 当尾结点为 -1 时结束 list[sum++] = FirstAdd;   // 记录所有AddressFirstAdd = Next[FirstAdd];  // 找下一个结点 }for(int i=0;i<sum-sum%K;i+=K){  // 每 K 个结点一个区间 for(int j=0;j<K/2;j++){  // 反转链表int t = list[i+j];list[i+j] = list[i+K-j-1];list[i+K-j-1] = t; }}for(int i=0;i<sum-1;i++)printf("%05d %d %05d\n",list[i],Data[list[i]],list[i+1]);printf("%05d %d -1\n",list[sum-1],Data[list[sum-1]]);return 0;
}

更多推荐

《数据结构》02

本文发布于:2024-03-10 15:01:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1728291.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据结构

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!