【发布时间】:2018-06-04 14:02:54
【问题描述】:
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
void add(struct Node *head, int n) {
Node *newNode = new Node;
newNode->data = n;
newNode->next = NULL;
Node *cur = head;
while(cur) {
if(cur->next == NULL) {
cur->next = newNode;
return;
}
cur = cur->next;
}
}
void display(struct Node *head) {
Node *list = head;
while(list) {
cout << list->data << " ";
list = list->next;
}
cout << endl;
cout << endl;
}
int main()
{
struct Node *newHead;
struct Node *head = new Node;
int ar[]={2,5,46,7,55};
for(int i=0; i<5;i++){
add(head,ar[i]);
}
display(head);
}
输出:
0 2 5 46 7 55
链表开头为零的原因是什么? 我该如何解决?我不想打印零。
如果您在我的代码中发现一些错误,请告诉我。我是编码新手。
【问题讨论】:
-
head也有一个未初始化的值。 -
在将
struct命名为 c++ 中的类型之前,您无需指定struct。struct是隐含的类型名称。 -
struct Node *head = new Node;您正在将一个具有未初始化值(您的编译器足以使其为 0)的节点添加到列表的开头。 -
你的老师好像还停留在90年代。您应该用一本好的 C++ 书籍来补充该课程。
标签: c++ linked-list output nodes