首页 > 解决方案 > 开始在 C++ 中实现 Linkedlist 类?

问题描述

对于作业,我必须实现列表类,并且在尝试设置头文件后遇到了许多错误。例如,在我定义引用 back() 和 front() 时会出现错误,说它们没有命名类型。

编辑:为 element_type 添加模板后,这些错误已修复

下面是我想出的默认构造函数......

#include "Linkedlist.h"
#include <cstddef> //need this to use NULL?

template<typename element_type>
Linkedlist<element_type>::Linkedlist()
{
    head->elem = 0;
    head->prev = NULL;
    head->next = NULL;
    tail = head;
}

我想我对这个类中 element_type 的使用没有很好的理解......但是,上面的默认构造函数是一个好的开始吗?它为我编译,但仍然可能存在一些我看不到的问题。我的教授给了我们如何定义节点结构的自由,唯一给出的是类的公共成员函数。

#ifndef LINKEDLIST_H
#define LINKEDLIST_H

using namespace std;

template<typename element_type>
class Linkedlist
{
public:


    typedef element_type& reference;
    typedef const element_type& const_reference;
    Linkedlist(); //default constructor for empty list
    ~Linkedlist(); //destructor to free nodes dynamically created to support 
    the linklist
    bool empty() const;
    void clear();
    reference back();
    const_reference back() const;
    reference front();
    const_reference front() const;
    Linkedlist& operator=(const Linkedlist& l);
    void pop_back ( );
    void pop_front ( );
    void push_back ( const element_type& x );
    void push_front ( const element_type& x );
    void sort ( );
    // constructor that initializes the linked list with n nodes,
    // with elem value from 0 to n-1
    explicit Linkedlist(unsigned int n);
    // print the linked list in the forward direction,
    // similar to the show function of lab6
    void check() const;
    // print the linked list in the backward direction,
    // similar to the reverse_show function of lab7
    void rcheck() const;
    // insert a node with value specified by x after the node
    // specified by pos. The first node has position 0.
    // if the number of nodes in the linked list is less than
    // pos, the node is inserted at the end.
    void insert(unsigned int pos, const element_type& x);
    // remove the node specified by pos.
    // if the number of nodes in the linked list is less than
    // pos, the node at the end if any is removed.
    void erase(unsigned int pos);

        struct Node
        {
            element_type elem;  // Data
            Node * next;        // Pointer to the next node in the chain
            Node * prev;        // Pointer to the previous node in the chain
        };
private:

    Node * head;
    Node * tail;

};

标签: c++linked-list

解决方案


比较。LinkedList_Linkedlist

现在您更改了问题并修正了错字:模板类应该在头文件中实现。

您显示的代码会导致很多错误,但不是您提到的错误。

template<typename element_type>
class Linkedlist
{ // ...
};

// ...

template <typename element_type>
Linkedlist<element_type>::Linkedlist()
{ // ...

...并取消注释typedefs。


推荐阅读