C++ 双链表笔记

#include <stdio.h>
#include <iostream>

//声明双链表节点
struct Node
{
    int x;
    int y;
    Node* next;                                                //定义一个结构体指针指向当前节点的下一个节点;
    Node* prev;                                                //定义一个结构体指针指向上一个节点;
};

//声明存放双链表指针结构体
struct Linklist                                                //双链表结构体;
{    
    Node* head;                                                //定义一个头节点指针;
    Node* tail;                                                //尾节点定义一个子节点指针;
    int size;                                                //定义变量来保存双链表中节点的数量;
};

//1.初始化一个双链表节点;
Node* createNode(int x, int y)                                //创建双链表子节点;
{
    Node* temp = (Node*)malloc(sizeof(Node));
    temp->x = x;                                            //将x赋值给结构体的x;
    temp->y = y;                                            //将y赋值给结构体的y    ;        
    temp->next = NULL;                                        //将前后节点都指向空地址;
    temp->prev = NULL;
    return temp;                                            //将创建好的结构体返回;
}

//2.链接2个节点; 
void node_link(Node*  n1, Node* n2)
{
    n1->next = n2;                                            //将n1的下一个节点指向n2
    n2->prev = n1;                                            //将n2的上一个节点指向n1

}

//3.初始化空的双链表; 
void  Linklist_init(Linklist *list)
{
        list->head = NULL;                                    //头指针为空;
        list->tail = NULL;                                    //尾指针也为空;
        list->size = 0;                                        //定义变量来保存节点中的节点的数量;
}


void push_head(Linklist* list, int x, int y)
{
    if (list->head == NULL)//判断双链表的头指针是否为空,则表示当前新建的是第一个节点
    {
        list->head = createNode(x, y);
        list->tail = list->head; //由于创建的是第一个节点,那么头节点和一个节点都是空;
        list->size = 1;        //双链表存放的节点大小变为1;
    }
    else
    {
        Node* temp = createNode(x, y);
        node_link(temp, list->head);
        list->head = temp;
        list->size++;
    }
}

void  push_end(Linklist* list, int x, int y)
{
    if (list->head == NULL)
    {
        list->head = createNode(x, y);
        list->tail = list->head; //由于创建的是第一个节点,那么头节点和一个节点都是空;
        list->size = 1;        //双链表存放的节点大小变为1;
    }
    else
    {
        Node*  temp= createNode(x, y);
        node_link(list->tail, temp);
        list->tail = temp;
        list->size++;
    }


}


int main()
{
    Linklist* list=(Linklist*)malloc(sizeof(Linklist));        //动态申请一个双链表;
    Linklist_init(list);                                    //初始化双链表;

    Node *temp1 = createNode(1, 1);
    Node *temp2 = createNode(2, 2);
    
    push_end(list,1,2);
    push_end(list, 2, 2);
    push_end(list, 3, 2);
    push_end(list, 4, 2);
    push_head(list, 4, 2);
    push_head(list, 4, 2);
    push_head(list, 4, 2);
    push_head(list, 4, 2);



    return 0;
}

猜你喜欢

转载自www.cnblogs.com/shenji/p/12514911.html