链接列表 - 插入列表的前面

时间:2014-09-22 01:14:31

标签: c++ linked-list

如何将一段数据(一个字符串)插入到链表的前面?没有删除或覆盖任何当前数据。

我正在上课的课程:

public:
        typedef size_t size_type;
        typedef node::value_type value_type;
        SuperList();
        bool isEmpty() const;
        bool isFull() const;
        void insertFront(string newItem); // will insert newItem to front

private:
        node* headptr;
        size_type howmany;

此节点类也包含在内,因此我可以使用它的任何功能。所有函数都在命名时执行(即addToEnd()将节点添加到结尾)

class node{
    public:
        // TYPEDEF
        typedef string value_type;

        // CONSTRUCTOR
        node(
            const value_type& init_data = value_type( ),
            node* init_link = NULL
        )
        { data_field = init_data; link_field = init_link; }

        // Member functions to set the data and link fields:
        void set_data(const value_type& new_data) { data_field = new_data; }
        void set_link(node* new_link)             { link_field = new_link; }

        // Constant member function to retrieve the current data:
        value_type data() const { return data_field; }

        // Two slightly different member functions to retreive
        // the current link:
        const node* link() const { return link_field; }
        node* link()             { return link_field; }

    private:
        value_type data_field;
        node* link_field;
};

// FUNCTIONS for the linked list toolkit
std::size_t list_length(const node* head_ptr);
void list_head_insert(node*& head_ptr, const node::value_type& entry);
void list_insert(node* previous_ptr, const node::value_type& entry);
node* list_search(node* head_ptr, const node::value_type& target);
const node* list_search(const node* head_ptr, const node::value_type& target);
node* list_locate(node* head_ptr, std::size_t position);
const node* list_locate(const node* head_ptr, std::size_t position);
void list_head_remove(node*& head_ptr);
void list_remove(node* previous_ptr);
void list_clear(node*& head_ptr);
void list_copy(const node* source_ptr, node*& head_ptr, node*& tail_ptr);
void addToEnd(node*& head, string newVal);
int position(node* head, string newVal);

2 个答案:

答案 0 :(得分:0)

此函数将返回一个新的链表,其中s为第一个元素,some_list为其余元素:

node *add_to_head(node *some_list, const string &s) {
   return new node(s,some_list);
}

<强>加入即可。现在我看到你有一个函数在头部插入一个元素。所以你应该简单地使用它:

list_insert(head_ptr, some_string);

list_insert函数可以像这样实现:

void list_insert(node *&head_ptr, const string &s) {
    head_ptr = new node(s, head_ptr);
}

答案 1 :(得分:0)

您可能需要考虑使链表类成为节点类的友元类,以便它可以访问节点成员,或者只是将节点类成员公开,因为这些是非常通用的成员。您显示的大部分功能也非常适用于列表类。

对于插入列表的前面,将新节点的下一个指针(你称之为链接字段)设置为列表的当前前端,然后将列表的前面设置为新节点。