静态链表的应用

简介

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

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;
}
相关推荐
深思慎考33 分钟前
从合并两个链表到 K 个链表:分治思想的递进与堆优化
数据结构·链表·递归··队列·合并链表
又见野草35 分钟前
软件设计师知识点总结:数据结构与算法(超级详细)
数据结构·算法·排序算法
曹牧4 小时前
C#:数组不能使用Const修饰符
java·数据结构·算法
大数据张老师4 小时前
数据结构——拓扑排序
数据结构
草莓工作室5 小时前
数据结构10:树和二叉树
数据结构
当战神遇到编程6 小时前
链表的概念和单向链表的实现
数据结构·链表
INGNIGHT7 小时前
单词搜索 II · Word Search II
数据结构·c++·算法
QuantumLeap丶9 小时前
《数据结构:从0到1》-06-单链表&双链表
数据结构·算法
violet-lz9 小时前
数据结构八大排序:快速排序-挖坑法(递归与非递归)及其优化
数据结构
Mrliu__10 小时前
Python数据结构(七):Python 高级排序算法:希尔 快速 归并
数据结构·python·排序算法