如何在不使用 C++ 函数的情况下显示链表中的元素

How can I display elements in the linked list without using function in C++?

本文关键字:情况下 显示 链表 元素 函数 C++      更新时间:2023-10-16

我想在链表中显示元素而不使用C++函数。我的代码没有出现在屏幕上的任何内容,即使它不包含任何错误。我不知道我该如何解决它?

#include <iostream>
using namespace std;
struct Element {
    int data;
    Element *next;
};
struct List {
    int nb_ele;
    Element *head;
    Element *tail;
};
int main(){
    Element *tmp;
    tmp = new(Element);
    tmp ->data = 5;
    tmp ->next = NULL;
    List *li;
    li ->head = tmp;
    li ->tail = tmp;
    li ->nb_ele = 1;
    tmp = new(Element);
    tmp ->data = 7;
    tmp ->next = li->head;
    li ->head = tmp;
    li ->nb_ele = li->nb_ele + 1;
    Element *ptr;
    ptr = li->head;
    while (ptr != NULL){
        cout<< ptr->data<<" ";
        ptr = ptr->next;
    }
}

你的代码的问题在于这一行:

List *li;

li 是一个未初始化的指针,当您稍后尝试访问它时,会导致问题。将此行更改为:

List *li = new List;

或者不要使用指针。 只需将其更改为:

List li;
相关文章: