By Jalan
知识工具需求
数学
数据结构和算法
- 链表
语言
- 在此强调一下.size()是unsigned
题干
给一个单链表,所有负数都得在整数前面出现,所有[0,K]的的在比K大的前面出现,别的顺序不能改.比如给:
18→7→-4→0→5→-6→10→11→-2 K==10
输出
-4→-6→-2→7→0→5→10→18→11.
输入条件
第一行有 首节点的地址 N<=10^ 5节点数,K<=10^ 3.
例1
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
输出条件
例1
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
题解
第一次
思路
- 用一个大数组nodeList保存链表
- 建立一个negativeList,KList,biggerThanKList,遍历这个链表.按Key的范围存到3个链表里
- 按顺序打印三个链表,注意打印格式和对每个表尾到下一个表头部的衔接.
预期时间复杂度
nlogn
编写用时
20分钟
代码
CPP
#include <iostream>
#include <stdio.h>
#include <vector>
using namespace std;
typedef struct node
{
int ad;
int key;
int next;
} node;
int main(int argc, char const *argv[])
{
//input
int firstAd, N, K;
cin >> firstAd >> N >> K;
vector<node> nodeList(100001);
for (int i = 0, ad, key, next; i < N; i++)
{
scanf("%d%d%d", &ad, &key, &next);
nodeList[ad] = {ad, key, next};
}
//process
vector<node> negativeList, KList, BiggerThanKList;
int nowAd = firstAd;
if (firstAd == -1)
{
return 0;
}
while (nowAd != -1)
{
if (nodeList[nowAd].key < 0)
{
negativeList.push_back(nodeList[nowAd]);
}
else if (nodeList[nowAd].key > K)
{
BiggerThanKList.push_back(nodeList[nowAd]);
}
else
{
KList.push_back(nodeList[nowAd]);
}
nowAd = nodeList[nowAd].next;
}
//output如果不想整衔接也可以直接改表里next的值,但是一样是要if半天的
int negativeSize = negativeList.size();
int KSize = KList.size();
int biggerSize = BiggerThanKList.size();
if (negativeSize)
{
for (int i = 0; i < negativeSize - 1; i++)
{
printf("%05d %d %05d\n", negativeList[i].ad, negativeList[i].key, negativeList[i + 1].ad);
}
printf("%05d %d ", negativeList[negativeSize - 1].ad, negativeList[negativeSize - 1].key);
if (KSize)
{
printf("%05d\n", KList[0].ad);
}
else if (biggerSize)
{
printf("%05d\n", BiggerThanKList[0].ad);
}
else
{
printf("-1\n");
}
}
if (KSize)
{
for (int i = 0; i < KSize - 1; i++)
{
printf("%05d %d %05d\n", KList[i].ad, KList[i].key, KList[i + 1].ad);
}
printf("%05d %d ", KList[KSize - 1].ad, KList[KSize - 1].key);
if (biggerSize)
{
printf("%05d\n", BiggerThanKList[0].ad);
}
else
{
printf("-1\n");
}
}
if (biggerSize)
{
for (int i = 0; i < biggerSize - 1; i++)
{
printf("%05d %d %05d\n", BiggerThanKList[i].ad, BiggerThanKList[i].key, BiggerThanKList[i + 1].ad);
}
printf("%05d %d -1", BiggerThanKList[biggerSize - 1].ad, BiggerThanKList[biggerSize - 1].key);
}
return 0;
}
运行用时
结尾
看在我写了这么多注释的份上可以给我点个赞嘛,求求惹=]砰砰砰,给我加点写下去的油呀@.@
也欢迎关注我的CSDN账号呀,接下来两个月我应该会按这个格式更新所有的PTA甲级题目
**开心code每一天**