[英]How can I display elements in the linked list without using function in C++?
I want to display elements in the linked list without using function in C++.我想在不使用 C++ 函数的情况下显示链表中的元素。 My code does not appear anything on the screen, even it does not contains any errors.
我的代码没有出现在屏幕上,即使它不包含任何错误。 I do not know how can I fix it?
我不知道我该如何解决?
#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;
}
}
The problem with your code is this line:您的代码的问题是这一行:
List *li;
li is an uninitialized pointer and when you try to access it later, causes problems. li 是一个未初始化的指针,当您稍后尝试访问它时,会导致问题。 change this line to:
将此行更改为:
List *li = new List;
or don't use a pointer.或者不使用指针。 simply change it to:
只需将其更改为:
List li;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.