欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C实现头插法和尾插法来构建非循环双链表(不带头结点)

程序员文章站 2022-04-27 19:19:13
在实际使用中,双链表比单链表方便很多,也更为灵活。对于不带头结点的非循环双链表的基本操作,我在《C语言实现双向非循环链表(不带头结点)的基本操作》这篇文章中有详细的实现。今天我们就...

在实际使用中,双链表比单链表方便很多,也更为灵活。对于不带头结点的非循环双链表的基本操作,我在《C语言实现双向非循环链表(不带头结点)的基本操作》这篇文章中有详细的实现。今天我们就要用两种不同的方式头插法和尾插法来建立双链表。

核心代码如下:

 

//尾插法创建不带头结点的非循环双向链表
Node *TailInsertCreateList(Node *pNode){

    Node *pInsert;
    Node *pMove;
    pInsert = (Node*)malloc(sizeof(Node));
    memset(pInsert, 0, sizeof(Node));
    pInsert->next = NULL;
    pInsert->prior = NULL;

    scanf("%d",&(pInsert->element));
    pMove = pNode;

    if (pInsert->element <= 0) {

        printf("%s函数执行,输入数据非法,建立链表停止\n",__FUNCTION__);
        return NULL;
    }

    while (pInsert->element > 0) {
        if (pNode == NULL) {
            pNode = pInsert;
            pMove = pNode;
        }else{

            pMove->next = pInsert;
            pInsert->prior = pMove;
            pMove = pMove->next;
        }

        pInsert = (Node *)malloc(sizeof(Node));
        memset(pInsert, 0, sizeof(Node));
        pInsert->next = NULL;
        pInsert->prior = NULL;
        scanf("%d",&(pInsert->element));
    }

    printf("%s函数执行,尾插法建立链表成功\n",__FUNCTION__);

    return pNode;
}

//头插法创建不带头结点的非循环双向链表
Node *HeadInsertCreateList(Node *pNode){

    Node *pInsert;
    pInsert = (Node *)malloc(sizeof(Node));
    memset(pInsert, 0, sizeof(Node));

    pInsert->next = NULL;
    pInsert->prior = NULL;
    scanf("%d",&(pInsert->element));

    if (pInsert->element <= 0) {

        printf("%s函数执行,输入数据非法,建立链表停止\n",__FUNCTION__);
        return NULL;
    }

    while (pInsert->element > 0) {
        if (pNode == NULL) {
            pNode = pInsert;
        }else{

            pInsert->next = pNode;
            pNode->prior = pInsert;
            pNode = pInsert;
        }

        pInsert = (Node *)malloc(sizeof(Node));
        memset(pInsert, 0, sizeof(Node));
        pInsert->next = NULL;
        pInsert->prior = NULL;
        scanf("%d",&(pInsert->element));
    }

    printf("%s函数执行,头插法建立链表成功\n",__FUNCTION__);
    return pNode;
}