我目前正在自学 C++,并尝试使用部分完整的指针在 C++ 中实现双向链表。我知道代码目前无法处理悬空节点或输出错误,我将在接下来实现这两者。但是,代码至少应该能够构造一个列表对象并向其添加元素。目前,当我尝试调用列表的构造函数时出现错误,表示我正在请求从 LinkedList* 转换为非标量类型 LinkedList。为什么我的列表被声明为指针?任何帮助将不胜感激,谢谢!
LinkedList.h
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
struct dataElement {
int key;
int id;
};
struct Node
{
dataElement data;
Node* next;
Node* prev;
};
class LinkedList
{
public:
/** Default constructor */
LinkedList();
/** Default destructor */
virtual ~LinkedList();
void addAtFront(int newElement);
void addAtBack(int newElement);
int removeTop();
int removeBottom();
int getTop();
int getBottom();
int findKey(int keyToFind);
protected:
private:
Node* head;
Node* tail;
int size;
};
#endif // LINKEDLIST_H
LinkedList.cpp
#include "LinkedList.h"
#include <iostream>
#include <stdlib.h>
LinkedList::LinkedList()
{
size = 0;
}
LinkedList::~LinkedList()
{
//dtor
}
void LinkedList::addAtFront(int newElement)
{
if (size == 0)
{
Node temp;
temp.data.id = newElement;
temp.data.key = 0;
head = &temp;
tail = &temp;
++size;
}
else
{
Node temp;
temp.data.id = newElement;
temp.data.key = size;
temp.next = head;
head->prev = &temp;
head = &temp;
++size;
}
}
void LinkedList::addAtBack(int newElement)
{
if (size == 0)
{
Node temp;
temp.data.id = newElement;
temp.data.key = 0;
head = &temp;
tail = &temp;
++size;
}
else
{
Node temp;
temp.data.id = newElement;
temp.data.key = 0;
tail->next = &temp;
temp.prev = tail;
tail = &temp;
++size;
}
}
LinkedListTest.cpp
#include "LinkedListTest.h"
#include "LinkedList.h"
int main()
{
LinkedList list = new LinkedList();
list.addAtFront(0);
}