[英]Can I implement a push_back method for linked list in that way?
我已經為這樣的鏈接列表做 push_back 方法:
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node* next;
Node(int data,
Node* next = nullptr){
this->data = data;
this->next = next;
}
};
Node* head = nullptr;
void push_back(int data){
if(head == nullptr){
head = new Node(data);
}
else{
Node *current = head;
while(current->next != nullptr){
current = current->next;
}
current->next = new Node(data);
}
}
但我想知道是否可以在另一個節點之后添加一個節點(我說的是這段代碼,見下文):
else{
Node *current = head;
while(current->next != nullptr){
current = current->next;
}
current->next = new Node(data);
}
不使用條件:
while(current->next != nullptr)
{current = current->next;}
,而是做:
while(current != nullptr){current = current->next;}
這樣做時,我們將當前指針均衡為一個 nullptr。 從那時起是否可以在末尾添加一個新節點並將該節點鏈接到整個列表?
還是while(current != nullptr)
的概念不利於 push_back()?
您可以通過將指針指向您希望更改的指針來執行類似的操作。
void push_back(int data){
Node** current = &head;
while(*current != nullptr) { current = &(*current)->next; }
*current = new Node(data);
}
作為獎勵,您不再有空列表的特殊情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.