双向链表

2023-10-11 21:08:29 浏览数 (1)

代码语言:javascript复制
#include<stdio.h>
#include<stdlib.h>
struct Node
{
    int data;
    struct Node* pre;
    struct Node* next;
};
struct Node* head;
Node* GetnewNode()
{
    Node* temp = (Node*)malloc(sizeof(Node));
    return temp;
}
void InsertheadNode(int x)
{
    Node* temp = GetnewNode();
    temp->data = x;
    temp->next = NULL;
    temp->pre = NULL;
    if (head == NULL)
    {
        head = temp;
        return;
    }
    head->pre = temp;
    temp->next = head;
    head = temp;
}
void Insertattail(int x)
{
    Node* temp = GetnewNode();
    temp->data = x;
    temp->next = NULL;
    temp->pre = NULL;
    Node* temp1 = head;
    while (temp1->next != NULL)
    {
        temp1 = temp1->next;
    }
    temp1->next = temp;
    temp->pre = temp1;
}
void Print()
{
    Node* temp = head;
    while (temp!=NULL)
    {
        printf("%d ", temp->data);
        temp = temp->next;
    }
    printf("n");
}
void ReversePrintf()
{
    Node* temp = head;
    if (temp == NULL)
    {
        return;
    }
    while (temp->next!=NULL)
    {
        temp = temp->next;
    }
    while (temp!=NULL)
    {
        printf("%d ", temp->data);
        temp = temp->pre;
    }
}
int main()
{
    InsertheadNode(2);
    Print();
    InsertheadNode(4);
    Print();
    InsertheadNode(6);
    Print();
    Insertattail(9);
    Insertattail(25);
    Print();
    ReversePrintf();
}

和单向链表差不多,只是多了一个指针域指向前面的节点

0 人点赞