c++在链表中添加项

C++ adding item onto a linked list

本文关键字:添加 链表 c++      更新时间:2023-10-16

我试图添加一个节点到链表(推函数)的开始。我得到两个错误:

1)从'Node int*'到'int'(指向test.Push(&test2); in main())

2)初始化参数1的'int Linked_List::Push(ItemType) [with ItemType = int]'(指向函数Push)

我真的不知道是什么问题。如果我去掉&out of test.Push(&test2); in main()然后我得到更多的错误,所以我认为它是正确的。

//.h
#ifndef Linked_List_h
#define Linked_List_h
template <typename ItemType>
class Node
{
    public:
        ItemType Data;
        Node <ItemType> *next;
};
template <typename ItemType>
class Linked_List
{
        public:
        Node <ItemType> *start;
        Linked_List();
        int Push(ItemType newitem);
};
#endif

.

//.cpp
#include "Linked_List.h"
template <typename ItemType>
Linked_List <ItemType>::Linked_List(){
    start = NULL;
}
template <typename ItemType>
int Linked_List <ItemType>::Push(const ItemType newitem){    //error
    Node <ItemType> *nnode;  //create new node to store new item
    nnode -> next = start -> next;  //new item now points previous first item of list
    start -> next = nnode;   //'start' pointer now points to the new first item of list
    return 1;
}
int main(){
    Linked_List <int> test;
    Node <int> test2;
    test2.Data = 4;
    test.Push(&test2);  //error
}

您的函数签名期望ItemType,在您的情况下是int:

int Push(ItemType newitem);

但是你正试图通过一个Node<ItemType>,因此你得到一个错误。

您的Push函数已经在内部创建了一个节点,因此您将直接将整数传递给它:

Linked_List <int> test;
int test2 = 4;
test.Push(test2);
我需要指出的是,除此之外,您的代码还有其他几个问题——对于初学者来说,这段代码:
Node <ItemType> *nnode;  //create new node to store new item
不是创建Node吗?它只是声明了一个指针。

我强烈建议你阅读c++的基础知识。

Push采用模板类型,因此在本例中为int。你要做的是像这样:

Linked_List<int> test;
test.push(4);