原题🔗在这里:1075 链表元素分类。
今天碰巧做到的一道关于链表操作的题目感觉还挺有意思的,不得不说陈越姥姥出的关于数据结构题都好有实用性,能让教材上很理论的东西在代码里实现出来,比如这道题需要的就是用到了很少见的——静态链表。
C++ Code
#include <iostream>
using namespace std;
const int M = 100001; // 结点个数不超过100000
// 原来的链表
int data1[M]; // data1[addr]存的是addr结点数据
int next1[M]; // next1[addr]存的是addr结点的后继地址
// 分类后的新链表
// M + 1是多了一个头结点 头结点地址为100001
struct List{
int data[M + 1];
int next[M + 1];
int head;
int tail;
List(int hh = 100001, int tt = 100001): head(hh), tail(tt){}
void insert(int node_addr, int node_data){ // 尾插法
data[node_addr] = node_data;
next[node_addr] = -1;
next[tail] = node_addr;
tail = node_addr;
}
void printL(){
int p = next[head];
while(p != -1){
printf("%05d %d ", p, data[p]);
if(next[p] == -1)
printf("-1\n");
else
printf("%05d\n", next[p]);
p = next[p];
}
}
};
int main(){
int first, N, K;
List l;
cin >> first >> N >> K;
for(int i = 0;i < N;i ++){ // 构建原来的链表
int Addr, Data, Next;
cin >> Addr >> Data >> Next;
data1[Addr] = Data;
next1[Addr] = Next;
}
int p = first; // 工作指针p
// 把所有负的先插在前面
while(p != -1){ // 不为空
if(data1[p] < 0)
l.insert(p, data1[p]);
p = next1[p];
}
// 接着插入非负但小于等于K的 注意等于K的这时也要纳入
p = first;
while(p != -1){
if(0 <= data1[p] && data1[p] <= K)
l.insert(p, data1[p]);
p = next1[p];
}
// 最后插入 >K 的
p = first;
while(p != -1){ // 不为空
if(data1[p] > K)
l.insert(p, data1[p]);
p = next1[p];
}
l.printL(); // 输出新链表
return 0;
}
提交结果


251

被折叠的 条评论
为什么被折叠?



