我写了这个程序来反转链表中的元素,在编译这个程序后,在reverse()中显示错误.为什么

I wrote this program to reverse the elements in a linked list, after compiling this program this is showing error in the reverse (). why?

本文关键字:程序 编译 reverse 显示 为什么 错误 链表 元素      更新时间:2023-10-16

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

错误显示:-在函数' void reverse() '中:|错误:没有匹配' 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;
}

这就是为什么每个编码标准都规定每行一个变量。

你写了什么:

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/c++中,您需要在每个指针变量名之前放置一个*。所以在reverse()中,第一行应该是:

Node* current, *prev, *nextaddress; // prev and nextaddress become Node *