单链表--游标实现

对于一些语言,没有指针,所以用数组是实现链表的一种方式

//链表的游标实现
//array数组分两部分,一部分为链表部分,有一个独立头节点,下标为1
//另一部分为freelist部分,也有独立的一个节点,下标为0,对于此部分,相当于一个栈
//进行malloc操作时,从开头(下标0后)取空间
//进行free操作时,被free的数放到开头(下标0后)
#define MAXN 10
struct node
{
    int element;
    int next;
};
void free(struct node array[],int position)
{
    array[position].next=array[0].next;
    array[0].next=position;
}
int malloc(struct node array[])
{
    int position;
    position=array[0].next;
    array[0].next=array[position].next;
    return position;
}
int FindpreviousofDelete(struct node array[],int head,int number)
{
    int position;
    position=head;
    while(array[array[position].next].element!=number&&array[position].next!=0)
        position=array[position].next;
    return position;
}
int FindpreviousofInsert(struct node array[],int head,int number)
{
    int position=head;
    while(array[position].next<=number&&array[position].next!=0)
        position=array[position].next;
    return position;
}
void Insert(struct node array[],int head,int number)
{
    int position=malloc(array);
    if(position==0){
        printf("Out of space!\n");
        return;
    }
    int former=FindpreviousofInsert(array,head,number);
    array[position].element=number;
    array[position].next=array[former].next;
    array[former].next=position;

}
void Delete(struct node array[],int head,int number)
{
    int position;
    position=FindpreviousofDelete(array,head,number);
    if(array[position].next==0){
        printf("Not exist!\n");
        return;
    }
    array[position].next=array[array[position].next].next;
    free(array,array[position].next);
}
int main()
{
    //新建
    struct node array[MAXN];
    int head=1;
    array[head].next=0;
    array[0].next=2;
    for(int i=2;i<MAXN-1;i++)
        array[i].next=i+1;
    array[MAXN-1].next=0;
    //插入
    Insert(array,head,10);
    //删除
    Delete(array,head,10);
    //查找
    //Find(array,head,2);
    //遍历
    //Print(array,head);

    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值