PAT (Basic Level) Practice (中文)1075 链表元素分类

该代码段使用C语言处理链表,首先按数据值小于0、小于等于k、大于k三个条件分别遍历链表,将节点存储到新的数组中,然后重新设置next域并输出排序后的链表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


AC代码

#include<stdio.h>
typedef struct{
    int add;
    int data;
    int next;
}node;
int main(){
    int fir,n,k,c=0;
    node origin[100000],sort[100000],temp;
    scanf("%d %d %d",&fir,&n,&k);
    for(int i=0;i<n;i++){
        scanf("%d %d %d",&temp.add,&temp.data,&temp.next);
        origin[temp.add]=temp;//用下标表示地址
    }
    temp=origin[fir];//第一次遍历,先找小于0的结点,连接成新的链表
    while(1){
        if(temp.data<0)sort[c++]=temp;
        if(temp.next==-1)break;
        else temp=origin[temp.next];
    }
    temp=origin[fir];//第二次遍历,找<=k的结点,在链表尾部连接
    while(1){
        if(temp.data>=0&&temp.data<=k)sort[c++]=temp;
        if(temp.next==-1)break;
        else temp=origin[temp.next];
    }
    temp=origin[fir];//第三次遍历,找>k的结点,在链表尾部连接
    while(1){
        if(temp.data>=0&&temp.data>k)sort[c++]=temp;
        if(temp.next==-1)break;
        else temp=origin[temp.next];
    }
    for(int i=0;i<c;i++){
        if(i!=c-1){//重置next域,再输出
            sort[i].next=sort[i+1].add;
            printf("%05d %d %05d\n",sort[i].add,sort[i].data,sort[i].next);
        }
        if(i==c-1){//最后节点的next域置为-1
            sort[i].next=-1;
            printf("%05d %d %d\n",sort[i].add,sort[i].data,sort[i].next);
        }
    }
    return 0;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Dragon_dd

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值