首页 > 解决方案 > 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++;
}

标签: c++linked-list

解决方案


推荐阅读