我正在尝试实现一个LinkedList构造函数,该构造函数将某些类型的向量作为参数并将其转换为链接列表。在测试中,我创建了一个整数(0-9)的向量并将其传递给构造函数。但是,当我尝试打印值而不是获取值时:{9,8,7,6,5,4,4,3,2,1,0}我正在获取{9,8,7,6,6,5,4, 3,2,1,019941456,0,}。每次随机数字都会变化。我不确定自己在做什么错,但是我确定这是我无法完全理解指针和地址的原因。我不确定如何解决它或从这里去哪里。抱歉,我是新手,不知道如何为文本加上颜色,谢谢。
链接列表类别
template<typename ElementType>
class LinkedList {
/*
* Declare any struct, class, or enum types you need to use here
*/
private:
typedef struct node {
ElementType val;
node *next;
node(ElementType input) : val(input), next(nullptr) {};
node() {};
}* LinkedListNode;
int list_size = 0; // size variable for ease
public:
LinkedListNode head; // Head of list
LinkedList(); // Default constructor
explicit LinkedList(const std::vector<ElementType> &values); // Initilize from vector
// Big 5
LinkedList(const LinkedList& source); // Copy constructor
LinkedList(LinkedList&& source) noexcept; // Move constructor
~LinkedList(); // Destructor
LinkedList<ElementType>& operator=(const LinkedList<ElementType>& source); // Copy assignment operator
LinkedList<ElementType>& operator=(LinkedList<ElementType>&& source) noexcept; // Move assignment operator
void push_front(ElementType value); // Push value on front
void push_back(ElementType value); // Push value on back
ElementType front() const; // Access the front value
ElementType back() const; // Access the back valueW
void pop_front(); // remove front element
void pop_back(); // remove back element
int size() const; // return number of elements
bool empty() const; // check if empty
void clear(); // clear the contents
void RemoveOdd(); // remove the odd elements from the list 0 indexed
bool operator==(const LinkedList<ElementType> &rhs) const;
.
.
.
};
构造方法:
template<typename ElementType>
LinkedList<ElementType>::LinkedList(const std::vector<ElementType> &values) {
if (values.size() == 0) {
head = NULL;
} else {
for (auto current_value : values) {
push_front(current_value);
}
}
}
push_front方法:
template<typename ElementType>
void LinkedList<ElementType>::push_front(ElementType value) {
LinkedListNode new_node = new node(value);
new_node -> next = head;
head = new_node; // Add to beginning
list_size++;
}