写在前面
- 实现思路
- 静态链表封装存储输入结点(
注意结构体变量
) - 初始化,循环计数有效结点个数、无效结点个数
- 序号赋值,结点排序
- 输出链表
- 其中,最后1个未删除结点、最后1个被删除节点单独处理
- 问题点
-
%05d
格式控制。-1特殊处理不能格式化输出 - 可能存在无效结点,即不在给出首地址开始的链表上
- 题目有1定难度,25分钟a题
测试用例
input:
00100 5
99999 -7 87654
23854 -15 00000
87654 15 -1
00000 -15 99999
00100 21 23854
output:
00100 21 23854
23854 -15 99999
99999 -7 -1
00000 -15 87654
87654 15 -1
ac代码
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
const int maxn = 100005;
const int table = 1000010;
// 定义静态链表
struct node
{
int address, data, next;
int order; // 结点在链表上的序号,无效结点记为2*maxn
} nodes[maxn];
// 绝对值是否已出现
bool isExist[table] = {false};
bool cmp(node a, node b) // 从小到大排序
{
return a.order < b.order;
}
int main()
{
// memset(isExist, false, sizeof(isExist));
fill(isExist, isExist+table, false);
for(int i=0; i<maxn; i++)
nodes[i].order = 2*maxn;
int n, bgin, address;
scanf("%d%d", &bgin, &n);
for(int i=0; i<n; i++)
{
scanf("%d", &address);
scanf("%d%d", &nodes[address].data, &nodes[address].next);
nodes[address].address = address;
}
// 有效结点个数和已删除有效节点个数
int countValid = 0, countRemoved = 0, p = bgin;
while(p!=-1)
{
if(!isExist[abs(nodes[p].data)])
{
isExist[abs(nodes[p].data)] = true;
nodes[p].order = countValid++;
}
else
nodes[p].order = maxn + countRemoved++;
p = nodes[p].next;
}
// 按order从小到大排序
sort(nodes, nodes+maxn, cmp);
int cnt = countValid + countRemoved;
for(int i=0; i<cnt; i++)
{
// 非最后1个节点
if(i!=countValid-1 && i!=cnt-1)
printf("%05d %d %05d\n", nodes[i].address, nodes[i].data, nodes[i+1].address);
else // 最后1个结点单独处理
printf("%05d %d -1\n", nodes[i].address, nodes[i].data);
}
return 0;
}
学习代码
- 思路1致,不再赘述
#include <cstdio>
#include <stdlib.h>
#include <algorithm>
using namespace std;
const int maxn = 100000;
struct NODE {
int address, key, next, num = 2 * maxn;
}node[maxn];
bool exist[maxn];
int cmp1(NODE a, NODE b){
return a.num < b.num;
}
int main() {
int begin, n, cnt1 = 0, cnt2 = 0, a;
scanf("%d%d", &begin, &n);
for(int i = 0; i < n; i++) {
scanf("%d", &a);
scanf("%d%d", &node[a].key, &node[a].next);
node[a].address = a;
}
for(int i = begin; i != -1; i = node[i].next) {
if(exist[abs(node[i].key)] == false) {
exist[abs(node[i].key)] = true;
node[i].num = cnt1;
cnt1++;
}
else {
node[i].num = maxn + cnt2;
cnt2++;
}
}
sort(node, node + maxn, cmp1);
int cnt = cnt1 + cnt2;
for(int i = 0; i < cnt; i++) {
if(i != cnt1 - 1 && i != cnt - 1) {
printf("%05d %d %05d\n", node[i].address, node[i].key, node[i+1].address);
} else {
printf("%05d %d -1\n", node[i].address, node[i].key);
}
}
return 0;
}
知识点小结
- 数据初始化
memset(isExist, false, sizeof(isExist));
fill(isExist, isExist+table, false);