c++在链表中添加项
C++ adding item onto a linked list
我试图添加一个节点到链表(推函数)的开始。我得到两个错误:
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);
相关文章:
- 将数组的元素添加到链表中
- 如何在链表末尾添加?
- 需要左键作为赋值的左操作数?? 在链表中添加Add_End、删除和Delete_Front?
- 将两个数字添加为链表
- 如何向自身添加链表?
- 如何将节点添加到链表
- 在 C++ 中使用 temp 变量将节点添加到链表的末尾
- 为什么我在尝试添加两个链表时出现此错误?
- 使用链表添加多项式?援助
- 将元素添加到 Head 的双链表
- 如何在链表前面添加和返回节点
- 编写递归算法以从链表中删除元素.编写递归算法以将元素添加到链表中
- 在 c++ 程序中调试链表以添加两个数字: 有人可以解释为什么 l3=l3->next;导致错误?
- 将新值添加到链表中
- C++添加到包含 char[] 作为参数的链表中
- 链表重载添加
- C++链表将新节点添加到列表的开头
- 排序后将数据添加到链表
- 如何将节点添加到链表C++的前面?我想多了这个概念
- 在c++中如何在静态数组的末尾添加链表