[英]insertion function to insert elements in a linked list at tail
我想實現在鏈表尾部插入元素,我想使用成員函數來實現,目前我可以通過在 struct 之外創建一個函數來實現,請幫助我應該修改什么來實現它作為成員功能。
我的傳統方法:
#include<iostream>
using namespace std;
struct node{
int data;
node *next;
};
node * Insert(int v,node *head){
if(head==NULL){
node *temp=new node;
head=temp;
temp->data=v;
temp->next=NULL;
return head;
}
else{
node *temp=head;
while(temp->next!=NULL){
temp=temp->next;
}
node *temp_new=new node;
temp_new->data=v;
temp_new->next=NULL;
temp->next=temp_new;
return head;
}
}
這是一個工作示例。 這個想法是,從成員函數中,您遞歸地調用node::Insert
直到到達最后一個元素,然后才創建下一個元素。
#include <iostream>
struct node{
int data;
node *next = nullptr;
node *Insert(int v);
};
node *node::Insert(int v)
{
if (next == nullptr)
{
next = new node;
next->data = v;
return next;
}
else
{
return next->Insert(v);
}
}
int main()
{
node a{3};
a.Insert(2);
a.Insert(5);
std::cout << a.data << ' ' << a.next->data << ' ' << a.next->next->data << ' ' << std::endl;
return 0;
}
另外: 避免using namespace std
。
添加
正如評論中所指出的,展開遞歸可能是一個好主意。 這是上述代碼的非遞歸版本:
#include <iostream>
struct node{
int data;
node *next = nullptr;
node *Insert(int v);
};
node *node::Insert(int v)
{
if (next == nullptr)
{
next = new node;
next->data = v;
return next;
}
else
{
auto p = next;
while (p->next != nullptr)
p = p->next;
p->next = new node;
p = p->next;
p->data = v;
return p;
}
}
int main()
{
node a{3};
a.Insert(2);
a.Insert(5);
std::cout << a.data << ' ' << a.next->data << ' ' << a.next->next->data << ' ' << std::endl;
return 0;
}
僅通過查看您的insert
當前所做的事情,將其作為node
的成員是沒有意義的。 你可以像這樣調用你的insert
:
node* root = nullptr;
root = Insert(42,root);
創建一個包含單個元素的列表。 另一方面,在擁有node
類型的實例之前,您不能調用node
的成員函數。
如果您編寫一個表示列表的類,而不僅僅是單個節點,則轉換會更簡單。 從這個開始:
struct node{
int data;
node *next;
};
struct linked_list {
node* head;
};
現在上面兩行看起來像這樣:
linked_list l;
l.insert(42);
您需要做的就是將 free 函數移動到類中,而不是使用參數head
而是使用成員head
。 也不再需要返回頭部:
#include<iostream>
using namespace std;
struct node{
int data;
node *next;
};
struct linked_list {
node* head = nullptr;
void Insert(int v){
if(head==nullptr){
head =new node;
head->data=v;
head->next=nullptr;
}
else{
node *temp=head;
while(temp->next!=nullptr){
temp=temp->next;
}
node *temp_new=new node;
temp_new->data=v;
temp_new->next=nullptr;
temp->next=temp_new;
}
}
};
請注意,我沒有對實現進行任何更改(只有NULL
-> nullptr
和void
返回,如果它有一個錯誤,那么它現在仍然有一個錯誤;)。 您還應該為node
和linked_list
以及析構函數提供適當的構造函數,因為目前這會泄漏所有分配的內存。 最后但並非最不重要的是,您需要閱讀 3/5 規則: 什么是三規則?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.