我编写了这个程序来反转链表中的元素,编译完这个程序后,它在reverse()中显示错误。为什么呢?
错误显示: - ||在函数'void reverse()'中:| | 40 |错误:'operator ='不匹配(操作数类型为'Node'和'long int')| | 40 |注意:候选人是:|
#include<iostream>
using namespace std;
struct Node
{
int data;
Node* next;
};
Node* head;
void insert(int data)
{
Node* newNode = new Node(); // create a new node
newNode->data = data;
newNode->next = NULL;
if(head == NULL ){ //if head is null, that means this is your first node
head = newNode; //so update the value of head
}else{
Node* temp = head;
while(temp->next!=NULL)
{
temp = temp->next;
}
temp->next = newNode;
}
}
void print()
{
Node* temp = head;
while(temp!=NULL)
{
cout<<" "<<temp->data<<" ";
temp = temp->next;
}
cout<<endl;
}
void reverse()
{
Node* current;
Node* prev;
Node* nextaddress;
current = head;
prev = NULL;
while(current!=NULL)
{
nextaddress = current->next;
current->next = prev;
prev = current;
current = nextaddress;
}
head = prev;
}
int main()
{
head = NULL;
int a, n;
cout<<"\n enter the number of elements to be stored into the list :";
cin>>n;
cout<<"\n enter those elements :";
for(int i=1; i<=n; i++)
{
cin>>a;
insert(a);
}
print();
cout<<"\n the reverse of the linkedlist is :";
reverse();
print();
return 0;
}
答案 0 :(得分:6)
这就是每个编码标准每行一个变量的原因。
你写的是什么:
Node* current , prev, nextaddress;
current = head;
prev = NULL;
你的意思是:
Node* current , * prev, * nextaddress;
// ^^ ^^ Without the star they are Node objects.
current = head;
prev = NULL;
你应该打字的是:
Node* current = head;
Node* prev = nullptr;
Node* nextaddress;
嘿,看起来它不会占用更多的空间。
答案 1 :(得分:1)
在C / C ++中,您需要在每个作为指针的变量名之前放置*
。因此,在reverse()
中,第一行应为:
Node* current, *prev, *nextaddress; // prev and nextaddress become Node *