将列表转换为节点指针

时间:2019-03-02 10:17:18

标签: search linked-list

我正在尝试编写一个函数来搜索元素的链表,但是当我尝试对其进行编译时,出现错误,提示cannot convert list to node* in assignment。为什么会这样呢?我的列表是否已经不是节点*?

代码:

#include <iostream> 
#include <stdio.h>
using namespace std;

struct node {
    int data;
    node * next;
};

class list {
    public:
        list();
    void createnode(int value);
    int size();
    void insert_position(int pos, int value);
    void delete_first();
    void delete_last();
    void remove(int pos);
    int get(int pos);
    int search(int searchNum);
    node * head, * tail;
};

list::list() {
    head = NULL;
    tail = NULL;
}

node * search(list l, int value) {
    node * p;
    for (p = l; p != nullptr; p = p - > next) {
        if (p - > data == value) return p;
    }
    return nullptr;
}

1 个答案:

答案 0 :(得分:0)

没有您的列表不是节点*。列表只是一个类。 您正在做的是将一个类对象分配给node *。

node * search(node* l, int value) {
    node * p;
    for (p = l; p != NULL; p = p -> next) {
        if (p -> data == value) return p;
    }
    return NULL;
}