双向链表

来源:互联网 发布:网络语66是什么意思 编辑:程序博客网 时间:2024/05/23 01:14
#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;    }}

0 0