链表-插入到列表的前面

Linked List - Inserting to front of the list

本文关键字:前面 列表 插入 链表      更新时间:2023-10-16

如何在链表的前面插入一段数据(字符串)?不删除或覆盖任何当前数据。

我正在学习的课程:

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;

这个节点类也包括在内,所以我可以使用它中的任何函数

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);

此函数将返回一个新的链表,其中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);
}

您可能需要考虑将链表类作为节点类的朋友类,这样它就可以访问节点成员,或者只将节点类成员公开,因为这些都是非常通用的成员。此外,您显示的大多数函数实际上都是为列表类准备的。

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