✍个人博客:https://blog.csdn.net/Newin2020?spm=1011.2415.3001.5343
📚专栏地址:PAT题解集合
📝原题地址:题目详情 - 1133 Splitting A Linked List (pintia.cn)
🔑中文翻译:链表元素分类
📣专栏定位:为想考甲级PAT的小伙伴整理常考算法题解,祝大家都能取得满分!
❤️如果有收获的话,欢迎点赞👍收藏📁,您的支持就是我创作的最大动力💪
1133 Splitting A Linked List
Given a singly linked list, you are supposed to rearrange its elements so that all the negative values appear before all of the non-negatives, and all the values in [0, K] appear before all those greater than K. The order of the elements inside each class must not be changed. For example, given the list being 18→7→-4→0→5→-6→10→11→-2 and K being 10, you must output -4→-6→-2→7→0→5→10→18→11.
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 (≤105) which is the total number of nodes, and a positive K (≤103). 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 in [−105,105], andNext
is the position of the next node. It is guaranteed that the list is not empty.Output Specification:
For each case, output in order (from beginning to the end of the list) the resulting linked list. Each node occupies a line, and is printed in the same format as in the input.
Sample Input:
00100 9 10 23333 10 27777 00000 0 99999 00100 18 12309 68237 -6 23333 33218 -4 00000 48652 -2 -1 99999 5 68237 27777 11 48652 12309 7 33218
Sample Output:
33218 -4 68237 68237 -6 48652 48652 -2 12309 12309 7 00000 00000 0 99999 99999 5 23333 23333 10 00100 00100 18 27777 27777 11 -1
题意
第一行给定链表的起始地址 h
、总结点数 n
和常量 k
。
要求将该链表划分成三个部分,将负数放在链表的最前面,正数放到负数的后面,并且数值范围在 [0,k]
的元素放在正数的前面,而大于 k
的元素放在正数的后面。
思路
具体思路如下:
- 先将结点信息存入数组当中,方便后续的调用。
- 准备三个数组
a,b,c
,分别存放负数元素的地址、[0,k]
之间的正数和大于k
的正数,然后从前往后遍历链表,将元素地址放入对应的数组中。 - 将三个数组合并成一个数组,然后输出最终结果即可。
代码
#include<bits/stdc++.h>
using namespace std;
const int N = 100010;
int h, n, k;
int e[N], ne[N];
int main()
{
//输入每个结点的信息
cin >> h >> n >> k;
for (int i = 0; i < n; i++)
{
int address, data, next;
scanf("%d%d%d", &address, &data, &next);
e[address] = data, ne[address] = next;
}
//对结点进行分类
vector<int> a, b, c;
for (int i = h; i != -1; i = ne[i])
{
int d = e[i];
if (d < 0) a.push_back(i);
else if (d <= k) b.push_back(i);
else c.push_back(i);
}
//将划分后的链表合并到一起
a.insert(a.end(), b.begin(), b.end());
a.insert(a.end(), c.begin(), c.end());
//输出最终链表
for (int i = 0; i < a.size(); i++)
{
printf("%05d %d ", a[i], e[a[i]]);
if (i + 1 == a.size()) puts("-1");
else printf("%05d\n", a[i + 1]);
}
return 0;
}