C语言实现数据结构中的双向链表

这里有博客中的所有源代码:Github项目地址

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

typedef int DataType;//双向链表中数据的类型
typedef struct DNode
{
    DataType element;
    struct DNode *prior,*next;
}DNode,*DoubleList;//定义双向链表中一个节点

DoubleList createDList()//创建双向链表
{
    DoubleList head,p1,p2;
    DataType data;
    scanf("%d",&data); // NOLINT
    if(data!=0)//初始化头结点
    {
        head=(DoubleList)malloc(sizeof(DNode));
        head->element=data;
        head->prior=NULL;
        head->next=NULL;
        p1=head;
    }
    else
    {
        return NULL;//如果是0的话,直接跳出去,后面的工作一律不再进行
    }
    scanf("%d",&data); // NOLINT
    while(data!=0)
    {
        p2=(DoubleList)malloc(sizeof(DNode));
        p2->element=data;
        p2->prior=p1;
        p2->next=NULL;
        p1->next=p2;
        p1=p2;
        scanf("%d",&data);                    // NOLINT
    }
    return head;
}

DoubleList delDList(DoubleList head,DataType data)//删除链表某个节点,该节点的值等于data
{
     DoubleList p;
    
    if(head==NULL)
    {
        return NULL;
    }
    if(data==0)
    {
        printf("please input the data which will be deleted!\n");
        scanf("%d",&data); // NOLINT
    }
    p=head;//让p指向头结点,p在双向链表上移动,完成相应的操作
    while(p!=NULL&& p->element!=data)//用p->element!=data而不是p->element=data,
    {                                //是想让p在循环的控制下,在双向链表上不断移动
        p=p->next;
    }
    if(p!=NULL)
    {
        if(p==head)//如果第一次的时候就跳出来的话,p肯定指向的是head
        {
            head=p->next;//删除头结点
            head->prior=NULL;
            free(p);
        }
        else
        {
            if(p->next==NULL)//已经找到最后一个节点了才找到
            {
                (p->prior)->next=NULL;
                free(p);
            }
            else //中间某个节点上找到了要删除的节点
            {
                p->prior->next=p->next; //语句1  1和2次序很关键,绝对不能颠倒
                p->next->prior=p->prior;//语句2
                free(p);
            }
        }
    }
    else
    {
        printf("we can not find the element that you want to find!\n");
    }
    return head;
}

void printDList(DoubleList head)
{
    DoubleList p=head;
    while(p!=NULL)
    {
        printf("%d\t",p->element);
        p=p->next;
    }
    printf("\n");
}

void freeDList(DoubleList head)
{
    DoubleList p;
    if(head==NULL)
    {
        return;
    }
    while(head!=NULL)
    {
        p=head->next;
        free(head);
        head=p;
    }
}

int main(void)
{
    DoubleList head;
    printf("please input the interge,and create the Doublelist! \n");
    head=createDList();
    printf("print the Doublelist you have created!\n");
    printDList(head);
    printf("delete the Doublelist!\n");
    head=delDList(head,0);//delDList()函数有返回值
    printf("print the Doublelist you have deleted!\n");
    printDList(head);
    freeDList(head);
}
转载自:http://blog.csdn.net/jasmine_shine/article/details/44033947

猜你喜欢

转载自blog.csdn.net/shiyipaisizuo/article/details/78994515