我编写了该程序来反转链接列表中的元素,编译该程序后,这在反向()中显示了错误。为什么?

错误显示:-
||在函数“void reverse()”中:|
| 40 |错误:与“operator =”不匹配(操作数类型为“节点”和“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;
}

最佳答案

这就是为什么每个编码标准都在每行中声明一个变量的原因。

你写的是:

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;

嘿,看起来它不再占用空间。

关于c++ - 我编写了该程序来反转链接列表中的元素,编译该程序后,这在反向()中显示了错误。为什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31399175/

10-12 22:20