創建雙鏈表


C代碼實現如下:

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

typedef struct DuLNode {
        int data;
        struct DuLNode *pre;
        struct DuLNode *next;
}DuLNode;

DuLNode *create_double_linked_list()
{
        int i;
        DuLNode *pheader,*p,*new;
        pheader = (DuLNode *)malloc(sizeof(DuLNode));
        if (pheader == NULL)
                return NULL;
        pheader->data = -1;
        pheader->pre = NULL;
        pheader->next = NULL;


        p = pheader;
        for (i=1; i<=10; i++) {
                new = (DuLNode *)malloc(sizeof(DuLNode));
                if (new == NULL)
                        return NULL;
                new->data = i;
                new->pre = p;
                new->next = NULL;

                p->next = new;
                p = new;
        }
        pheader->next->pre = p;
        p->next = pheader->next;

        return pheader;
}

int print_double_linked_list(DuLNode *phead)
{
        DuLNode *p;

        if(phead == NULL || phead->next == NULL)
                return -1;

        p = phead->next;
        while(phead->next != p->next) {
                printf("%d ", p->data);
                p = p->next;
        }
        printf("%d\n", p->data);

        return 0;
}

int delete_double_linked_list(DuLNode *phead)
{
        if(phead == NULL || phead->next == NULL)
                return -1;

        free(phead);

        return 0;
}

int main()
{
        DuLNode *phead;
        phead = create_double_linked_list();
        print_double_linked_list(phead);
        delete_double_linked_list(phead);


        return 0;
}

發佈了30 篇原創文章 · 獲贊 47 · 訪問量 28萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章