c++ - LinkedList 向量构造函数未按预期工作
问题描述
我正在尝试实现一个 LinkedList 构造函数,它将某种类型的向量作为参数并将其转换为链表。在我的测试中,我创建了一个整数向量(0-9)并将其传递给我的构造函数。但是,当我尝试打印出值而不是得到: {9, 8, 7, 6, 5, 4, 3, 2, 1, 0} 我得到 {9, 8, 7, 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++;
}
解决方案
推荐阅读
- javascript - 表单验证 - 反应
- excel - 在 MailItem.Attachments.Add 失败后尝试显示 MailItem 时,Outlook 数组索引超出范围
- android - dataSnapshot if else 继续循环
- mysql - 如何创建查看多个表的“插入前”触发器
- flutter - Flutter bool name = String 可能吗?
- memory-leaks - F# 中的计算是否在完成时调用 Dispose()?
- ios - 如何自定义 UICollectionView Cell 以显示图像网格,如附件所示?
- javascript - 按照用户使用 Java Script 将鼠标悬停在它们上的顺序打印消失的悬停数字
- html - css 过渡在我的卡 div 上无法正常工作
- json - 如何使用 Ktor 解析响应