数据结构双链表基本操作

双链表:

主要注意最后结点的操作,否则容易出现NULL->prior的情况。

#include <stdio.h>
#include <stdlib.h>

typedef struct DLNode
{
    int data;
    struct DLNode *prior;
    struct DLNode *next;
}DLNode,*List;
//尾插法构建
void createndList(List &L,int a[], int n)
{
    List f,l;
    L=(List)malloc(sizeof(DLNode));
    f=L;
    int i;
    for(i=0;i<n;i++)
    {
        l=(List)malloc(sizeof(DLNode));
        l->data=a[i];
        //尾插法
        f->next=l;
        l->prior=f;
        f=l;
    }
    f->next=NULL;
    
}
void creatfirstList(List &L,int a[],int n)
{
    L=(List)malloc(sizeof(DLNode));
    List f,s;
    f=L;
    f->next=NULL;
    int i;
    for(i=0;i<n;i++)
    {
        s=(List)malloc(sizeof(DLNode));
        s->data=a[i];
        
        s->prior=f;
        s->next=f->next;
        f->next=s;
        //最初的末指针是空,没前驱指针
        if(i!=0)
           f->next->next->prior=s;
    }
    
}
//查找某元素值,返回位置
int find(List L,int x)
{
    List s;
    s=L->next;
    int i=0;
    while(s)
    {
        if(s->data==x)
            return i;
        s=s->next;
        i++;
    }
    return -1;
}
//删除x
void deletelist(List &L,int x)
{
    List s;
    s=L->next;
    while(s)
    {
        if(s->data==x)
        {
            if(s->next!=NULL)
            {
                s->next->prior=s->prior;
                s->prior->next=s->next;
                
            }
            else
                s->prior->next=NULL;
            free(s);
        }
        s=s->next;
    }
}
//输出
void pri(List L)
{
    List s;
    s=L->next;
    while(s!=NULL)
    {
        printf("%d\n",s->data);
        s=s->next;
        
    }
}
//插入,根据位置x插入n
void insert(List &L,int x,int n)
{
    List s,l;
    l=L;
    s=(List)malloc(sizeof(DLNode));
    s->data=n;
    int i;
    for(i=0;i<=x-1;i++)
    {
        if(l->next==NULL)
        {
            printf("数据插入位置过大");
            return;
        }
        l=l->next;
    }
    if(l->next!=NULL)
    {
        s->next=l->next;
        s->prior=l;
        l->next->prior=s;
        l->next=s;
    }
    else
    {
        s->next=NULL;
        l->next=s;
    }
}
int main()
{
    List L;
    int a[5]={1,2,3,4,5};
    creatfirstList(L, a, 5);
    int x;
    //x=find(L, 1);
    //deletelist(L, 1);
    insert(L, 1, 99);
    //printf("%d",x);
    pri(L);
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值