2014-09-22 15 views
0

如何将一段数据(字符串)插入链表的前面?没有摆脱或覆盖任何当前数据。链接列表 - 插入列表的前面

类我工作:

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

你的问题没有很好的定义。你认为哪一方面是前方?哪一端是后面?根据你的函数声明,它看起来像是头部和尾部(或尾部)。 – thang 2014-09-22 01:49:38

回答

0

这个函数将返回S作为第一要素和some_list作为休息一个新的链接列表(即addToEnd()添加一个节点到最后。):

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); 
} 
+0

函数原型是无效的,所以我不允许返回任何东西 – flowinwind 2014-09-22 01:39:59

+0

是的,我想出来之前,你更新它,但是这是工作:P – flowinwind 2014-09-22 17:10:36

0

你可能要考虑做链表类朋友类节点类,因此它可以访问节点成员,或只是公开节点类成员,因为这些是非常通用的成员。你显示的大部分功能都是为列表类准备的。

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