双向链表

#include<stdio.h>
#include<stdlib.h>
typedef int type;
typedef struct Dnode
{
    type info;
    struct Dnode*prior;
    struct Dnode*next;
}dnode;
//返回一个建立的双链表头指针,head->next=NULL,head->prior-NULL;
dnode* init()
{
    dnode*head=(dnode*)malloc(sizeof(dnode));
    head->next=head->prior=NULL;
    return head;
}
//创建有n个节点的双链表返回头指针
dnode* create(dnode*head,int n)
{
    dnode*pre,*q=head;
    while(n--){
        pre=(dnode*)malloc(sizeof(dnode));
        printf("input:");
        scanf("%d",&pre->info);
        q->next=pre;
        pre->prior=q;
        q=pre;
    }
    pre->next=NULL;
    return head;
}
//打印双链表
void display(dnode*head)
{
    if(!head)
        printf("empty\n");
    else{
        dnode*p=head->next;
        while(p){
            printf("%5d",p->info);
            p=p->next;
        }
        printf("\n");
    }
}
//销毁整个双链表
void destory(dnode*head)
{
    int i=1;
    if(!head)
        printf("empty\n");
    else{
        dnode*p=head,*q;
        while(p){
            // printf("%d is destory\n",i++);
            q=p->next;
            free(p);
            p=q;
        }
    }
}
//查找pos位置节点的指针,pos为0返回头指针
dnode*find(dnode*head,int pos)
{
    int i=1;
    dnode*pre=head->next;
    if(pos==0)return head;
    if(pos<0){
        printf("not\n");
        return NULL;
    }
    else{
        while(pre&&i<pos){
            pre=pre->next;
            i++;
        }
        if(i<pos){
            printf("not\n");
            return NULL;
        }
        else{
            return pre;
        }
    }
}
//返回尾指针
dnode *rear(dnode*head)
{
    dnode*pre=head;
    while(pre->next)
        pre=pre->next;
    return pre;
}
//在pos位置节点后面插入一个数据为x的节点,pos为零则在头节点后插入
void insert(dnode*head,int pos,type x)
{
    dnode*F=find(head,pos),*p;
    if(pos<0||!F)
        printf("not\n");
    else{
       p=(dnode*)malloc(sizeof(dnode));
       p->info=x;
       p->next=F->next;
       if(F->next)F->next->prior=p;
       p->next=F->next;
       F->next=p;
       p->prior=F;
    }
}
//删除pos位置的节点
void dele(dnode*head,int pos)
{
    dnode*F=find(head,pos);
    if(pos<1||!F)
        printf("not\n");
    else{
        F->prior->next=F->next;
        if(F->next)F->next->prior=F->prior;
        free(F);
    }
}
//将p2链表连接到p1后面
void merge(dnode*p1,dnode*p2)
{
    dnode*rear1=rear(p1);
    rear1->next=p2->next;
    p2->next->prior=rear1;
    free(p2);
}
//查找值为x的节点的指针
dnode*Find(dnode*head,type x)
{
    dnode*p=head->next;
    while(p&&p->info!=x)
        p=p->next;
    if(p)
        return p;
    else {
        printf("not");
        return NULL;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值