静态链表的应用

简介

静态链表也是由数据域与指针域两部分组成的一个结构体,只不过指针域是由整数下标表示

cpp 复制代码
struct node{
      int data;//数据域
      int next;//指针域
      };

求两个链表首个公共结点的地址

cpp 复制代码
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn=100000000;
struct node{
   char data;
    int next;
    bool flag;
}nodes[maxn];
int main(){
    for(int i=0;i<maxn;i++)
    nodes[i].flag=false;
    int addr1,addr2,n;//链表1的首地址addr1、个数n,链表2的首地址addr2
    scanf("%d%d%d",&addr1,&addr2,&n);
    int addr,next;
    char data;
    for(int i=0;i<n;i++){//将链表信息边输入边存入
        scanf("%d%s%d",&addr,&data,&next);
        nodes[addr].data=data;
        nodes[addr].next=next;
    }
    int j;
    for( j=addr1;j!=-1;j=nodes[j].next)//遍历链表1,
    nodes[j].flag=true;//改flag为true
    for( j=addr2;j!=-1;j=nodes[j].next){//遍历链表2
        if(nodes[j].flag==true) break;//找到在链表1中首个出现过的结点
    }
    if(j!=-1) printf("%05d\n",j);//返回结点地址
    else printf("-1\n");
    return 0;
}

由小到大输出静态链表

cpp 复制代码
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn=100000;
struct node{
    int now;
    int data;
    int next;
    bool flag;
}nodes[maxn];
bool cmp(node a,node b){//排序后,flag==true都在flag==false左端
    if(a.flag==false||b.flag==false)//碰到无效结点排序
    return a.flag>b.flag;//true在前,false在后
    else return a.data<b.data;//给结点排序
}
int main(){
    for(int i=0;i<maxn;i++)
    nodes[i].flag=false;
    int begin,num;
    scanf("%d%d",&begin,&num);
    int addr1,data,addr2;
    for(int i=0;i<num;i++){
        scanf("%d",&addr1);
        scanf("%d%d",&nodes[addr1].data,&nodes[addr1].next);
        nodes[i].now=addr1;
    }
    int position=begin,count=0;
    while(position!=-1){
        nodes[position].flag=true;//标记
        count++;
        position=nodes[position].next;
    }
    if(count==0)
    printf("0 -1\n");
    else{
        sort(nodes,nodes+maxn,cmp);//地址不连续,只能全部都考虑
        printf("%d %d\n",count,nodes[0].now);//输出首个地址
        for(int i=0;i<count;i++){
            if(i!=count-1)
        printf("%d %d %d\n",nodes[i].now,nodes[i].data,nodes[i].next);
        else
        printf("%d %d -1\n",nodes[i].now,nodes[i].data);
        }
    }
    return 0;
}
相关推荐
lifallen6 小时前
Paimon LSM Tree Compaction 策略
java·大数据·数据结构·数据库·算法·lsm-tree
秋说11 小时前
【PTA数据结构 | C语言版】线性表循环右移
c语言·数据结构·算法
minji...14 小时前
数据结构 算法复杂度(1)
c语言·开发语言·数据结构·算法
black_blank15 小时前
st表 && csp37 第四题 集体锻炼
java·数据结构·算法
我爱Jack15 小时前
Java List 使用详解:从入门到精通
java·开发语言·数据结构
秋说15 小时前
【PTA数据结构 | C语言版】在顺序表 list 的第 i 个位置上插入元素 x
c语言·数据结构·list
楼田莉子16 小时前
数据学习之队列
c语言·开发语言·数据结构·学习·算法
秋说16 小时前
【PTA数据结构 | C语言版】返回单链表 list 中第 i 个元素值
c语言·数据结构·list
雾里看山16 小时前
数据结构之队列
数据结构
双叶83617 小时前
(C++)任务管理系统(正式版)(迭代器)(list列表基础教程)(STL基础知识)
c语言·开发语言·数据结构·c++·list