C++ 双链表理解

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

typedef struct Link
{
    int data;
    Link* last;  //前驱指针
    Link* next; //后继指针
}link;


struct DataStore
{
    link* head; //头节点指针
    link* end; //尾节点指针
    int size;
};

DataStore* init_DataStore() //初始化双链表
{
    DataStore* list = (DataStore*)malloc(sizeof(DataStore));
    list->head = NULL;
    list->end = NULL;
    list->size = 0;
    return list;

}

//初始化双链表节点
link*  init_Node(int x)
{
    link* temp = (link*)malloc(sizeof(link));
    temp->data = x;
    temp->next = NULL;
    temp->last = NULL;
    return temp;
}

//双链表节点链接
void link_Node(link* n1, link* n2)
{
    n1->next = n2;
    n2->last = n1;
}

//将链表链接双链表data中
DataStore*  link_head(DataStore* data, link* temp1)
{
    DataStore* temp = data;  
    if (temp->size == 0)
    {
        temp->head = temp1;
        temp->end = temp1;
        temp->size = 1;
    }
    else
    {
        link_Node(temp1, temp->head);
        temp->head = temp1;
        temp->size++;
    }
    return temp;
}

DataStore* push_end(DataStore* data, link* temp1)
{
    DataStore* temp = data;
    if (temp->head==NULL)
    {
        temp->head = temp1;
        temp->end = temp->head;
        temp->size = 1;
        return temp;
    }
    else
    {
        link_Node(temp->end, temp1);
        temp1->last = temp->end;  //将temp1的前驱挂在尾节点上,
        temp->end = temp1;       //尾节点的值现在指向temp1
        temp->size++;
        return temp;
    }

}



void print_list(DataStore* list)
{
    link* temp = list->head;
    while (temp != NULL)
    {
        printf("%d->", temp->data);
        temp = temp->next;

     }
    printf("NULL\n");
}


void printf_list_end(DataStore* list)
{

    Link* temp = list->end;
    while (temp != NULL)
    {
        printf("%d->", temp->data);
        temp = temp->last;
    }
    printf("NULL\n");
}

int main()
{
//  DataStore* data1=init_DataStore();
    link* temp1 = init_Node(1);
    link* temp2 = init_Node(2);
    link* temp3 = init_Node(3);
    link* temp4 = init_Node(4);
    link* temp5 = init_Node(5);
//      link_head(data1, temp1);    //将双链表存放到
//      link_head(data1, temp2);
//  link_head(data1, temp3);
//  link_head(data1, temp4);
//  link_head(data1, temp5);
//  //link_Node(temp1, temp2);   //双链表节点之间的链接
//  print_list(data1);
//  printf_list_end(data1);

    DataStore* data2 = init_DataStore();
    push_end(data2, temp1); //将双链表存放到
    push_end(data2, temp2);
    push_end(data2, temp3);
    push_end(data2, temp4);
    push_end(data2, temp5);
    print_list(data2);
    printf_list_end(data2);


    return 0;
}

  

原文链接: https://www.cnblogs.com/shenji/p/12521499.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    C++ 双链表理解

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/336265

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月1日 下午10:34
下一篇 2023年3月1日 下午10:34

相关推荐