可以帮我看一下怎么创建双向链表吗?C++


struct List
{
    int val;
    List* next;  //指向前的指针
    List* pre;   //指向后的指针
};

void Creat(List* L)     //单链表的创建
{
    int cur;
    cin >> cur;

    while (cur != -1)
    {
        List* p;
        p = (struct List*)malloc(sizeof(List));
        p->val = cur;
        p->next = NULL;
        L->next = p;
        L = L->next;
        cin >> cur;
    }
}

双链表就是在单链表的基础上,先把头节点pre设为nullptr,在20行之后加上p->pre=L就可以。
还有,如果是C++的话,不建议使用C的语法,建议使用nullptr代替NULL,用new 代替malloc,delete代替free。

#include <iostream>

using namespace std;

struct List
{
    int val;
    List *prev;
    List *next;
};

List *create()
{
    List *head = nullptr;
    List *tail = nullptr;
    int val;
    while (cin >> val)
    {
        if (val == -1)
            break;
        List *p = new List;
        p->val = val;
        p->next = nullptr;
        if (!head)
        {
            head = p;
            tail = p;
        }
        else
        {
            tail->next = p;
            p->prev = tail;
            tail = p;
        }
    }
    return head;
}

void destroy(List *head)
{
    while (head)
    {
        List *p = head;
        head = head->next;
        delete p;
    }
}

void print(List *head)
{
    while (head)
    {
        cout << head->val << ' ';
        head = head->next;
    }
    cout << '\n';
}

int main()
{
    List *head = create();
    print(head);
    destroy(head);
    return 0;
}
$ g++ -Wall main.cpp
$ ./a.out
1 2 3 4 5 -1
1 2 3 4 5

供参考:

#include <iostream>
using namespace std;
struct List
{
    int   val;
    List* next;  //指向前的指针
    List* pre;   //指向后的指针
};

void Creat(struct List*& L) //单链表的创建
{
    int cur;
    List* p = NULL, * tail = NULL;
    while (cin >> cur && cur != -1)
    {
        p = new struct List;  //(struct List*)malloc(sizeof(List));
        p->pre = NULL;
        p->next = NULL;
        p->val = cur;
        if (L == NULL) {
            L = p;
        }
        else {
            p->pre = tail;
            tail->next = p;
        }
        tail = p;
    }
}
void print(struct List* L)
{
    struct List* p = L, * pr = NULL;
    while (p) {
        cout << p->val << " ";
        pr = p;
        p = p->next;
    }
    cout << endl;
    while (pr) {
        cout << pr->val << " ";
        pr = pr->pre;
    }
    cout << endl;
}
int main()
{
    struct List* L = NULL;
    Creat(L);
    print(L);
    return 0;
}