【问题标题】:Linked list (invalid conversion from 'Node<int>*' to 'int' [-fpermissive]|) in C++C++ 中的链表(从 'Node<int>*' 到 'int' [-fpermissive]| 的无效转换)
【发布时间】:2021-08-28 15:59:00
【问题描述】:

这是我在链接列表中插入新节点时遇到的问题。我在第 73 行遇到错误:

[错误] 从 'Node*' 到 'int' 的无效转换 [-fpermissive]

#include<iostream>
using namespace std;

struct Node{
    int data;
    Node *next;
    Node(int x){
        data = x;
        next= NULL;
    }
};

void trans(Node *head){
    if(head!=NULL){
        cout<<head->data<<"->";
        trans(head->next);
    }
    
}

Node * insert(Node *head, int x){
    
    Node *n = new Node(x);
    n->next = head;
    return n;
    
}

Node * insertend(Node *head, int x){
    Node *temp = new Node(x);
    if(head==NULL)
        return temp;
    Node *curr = head;
    while(curr->next!=NULL)
        curr= curr->next;
    curr->next = temp;
    return head;
}

Node *del(Node *head){
    if(head==NULL){
        return NULL;
    }
    else{
        Node *temp =  head->next;
        delete head;
        return temp;
        
    }
}

 int  search(Node *head, int x){
    int pos =1;
    Node *curr = head;
    while(head!=NULL){
        if(head->data ==x)
            {
             return pos;
             }
        else{
            pos++;
            head = head->next;
         }
         
     }
     return -1;
 }

Node insertPos(Node *head, int pos, int data){
    Node *temp = new Node(data);
    if(pos==1){
        temp->next = head;
        return temp;
    }
    Node *curr = head;
    for(int i =1; i<=pos-2 && curr!=NULL; i++){
        curr = curr->next;
    }
    if(curr==NULL){
        return head;
    }
    temp->next = curr->next;
    curr->next = temp;
    return head;
}

int main()
{
    Node *head = new Node(10);
    head = insert(head , 5);
    head = insert(head, 4);
    head = insert(head, 3);
    head =insert(head, 2);
    head = insertend(head, 6);
    head = insertPos(head, 4, 54);
    trans(head);
    cout<<endl;
    cout<<search(head, 4);

    return 0;
}

【问题讨论】:

  • 你的函数定义返回类型是 Node insertPos 应该是 Node* insertPos
  • 您能在上下文中显示整个错误消息吗?您是否期望 SO 用户应该计算行数?
  • 还为所有具有一个参数的构造函数添加关键字“explicit”。否则编译器可能会尝试使用诸如“类型转换器”之类的构造函数。
  • 重复自己以绕过警告您发布了一个写得不好的问题并不会改变您有太多代码来处理文本量的事实。您应该愿意使用不止一句话来描述您的问题并将您的代码简化为minimal reproducible example。语法错误很少需要十几行,通常不超过一半。

标签: c++ linked-list singly-linked-list


【解决方案1】:
Node insertPos(Node *head, int pos, int data)

应该是:

Node* insertPos(Node *head, int pos, int data)

显示以下终端输出的更改: 2->3->4->54->5->10->6-> 3

【讨论】:

    猜你喜欢
    • 2019-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-22
    • 1970-01-01
    • 2016-06-06
    • 1970-01-01
    相关资源
    最近更新 更多