我制作了c++程序,将数字作为输入,直到它们输入零,并将它们保存为链表,稍后再打印,但我不明白为什么会出现这些错误。
这是代码:
#include <iostream>
using namespace std;
struct Node
{
int data;
Node* next;
};
int main()
{
Node* head = NULL, temp1, temp2;
int data = 1;
while(data)
{
cout<<"Enter number or 0 if you want to end : "<<endl;
cin>>data;
temp1 = (Node*)malloc(sizeof(Node));
temp2 = temp1;
if(head==NULL)
head = temp1;
else
temp2->next = temp1;
}
Node* temp1 = head->next;
while(temp1->next != NULL)
{
cout<<temp1->data<<endl;
temp1 = temp1 -> next;
}
return 0;
}
我得到这些错误:
test.cpp: In function 'int main()':
test.cpp:18:41: error: no match for 'operator=' (operand types are 'Node' and 'Node*')
temp1 = (Node*)malloc(sizeof(Node));
^
test.cpp:4:8: note: candidate: constexpr Node& Node::operator=(const Node&)
struct Node
^~~~
test.cpp:4:8: note: no known conversion for argument 1 from 'Node*' to 'const Node&'
test.cpp:4:8: note: candidate: constexpr Node& Node::operator=(Node&&)
test.cpp:4:8: note: no known conversion for argument 1 from 'Node*' to 'Node&&'
test.cpp:21:17: error: cannot convert 'Node' to 'Node*' in assignment
head = temp1;
^~~~~
test.cpp:23:15: error: base operand of '->' has non-pointer type 'Node'
temp2->next = temp1;
^~
test.cpp:25:10: error: conflicting declaration 'Node* temp1'
Node* temp1 = head->next;
^~~~~
test.cpp:12:23: note: previous declaration as 'Node temp1'
Node* head = NULL, temp1, temp2;
^~~~~
test.cpp:26:15: error: base operand of '->' has non-pointer type 'Node'
while(temp1->next != NULL)
^~
test.cpp:28:18: error: base operand of '->' has non-pointer type 'Node'
cout<<temp1->data<<endl;
^~
test.cpp:29:21: error: base operand of '->' has non-pointer type 'Node'
temp1 = temp1 -> next;
^~
这种方法会让你把它附加到列表的开头。。。我不愿意直接回答你。。。但希望这能有所帮助!
分配节点:W/新节点((
将用户数据插入新节点的数据变量
使新节点指向头指针(new_node->next(
重新调整指向新节点的头指针(使其成为新的头(