void insertAtTop(node** head, int value){
node* temp=new node();
temp->data=value;
temp->next=*head;
*head=temp;
}
void insertAtLast(node*head, int value){
while(head->next!=NULL){
head=head->next;
}
node*temp=new node();
temp->data=value;
temp->next=NULL;
head->next=temp;
}
我不明白为什么您需要使用指向指针的指针来更改头部,但是如果您想在其他位置添加元素,则只需发送node* head
而不是即可node** head
。就像for insertatLast
node*head
as一样有效,但是如果我这样做insertAtTop
也不会。
您可以同时实现insertAtTop
并insertAtLast
同时使用pass by reference
和pass by value
。我建议您阅读按引用传递和按值传递之间的区别。您也可以阅读此内容。
我假设head
被声明为node* head;
通过参考传递:
void insertAtTop(node** head, int value){
node* temp=new node();
temp->data=value;
temp->next=*head;
*head=temp;
}
呼叫: insertAtTop(&head, value);
void insertAtLast(node** head, int value){
node* h = *head;
while(h->next!=NULL){
h = h->next;
}
node* new_node=new node();
new_node->data=value;
new_node->next=NULL;
h->next=new_node;
}
呼叫: insertAtLast(&head, value);
按值传递:
node* insertAtTop(node* head, int value){
node* temp=new node();
temp->data=value;
temp->next= head;
head = temp;
return head;
}
呼叫: head = insertAtTop(head, value);
node* insertAtLast(node* head, int value){
node* original_head = head;
while(head->next!=NULL){
head=head->next;
}
node*temp=new node();
temp->data=value;
temp->next=NULL;
head->next=temp;
return original_head;
}
呼叫: head = insertAtLast(head, value);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句