簡體   English   中英

C++個鏈表節點

[英]C++ linked list nodes

我對 C++ 的鏈表有非常基本的概念。這里我鏈接了節點,但我的想法是刪除最后一個節點,我該如何實現?

這是旨在刪除最后一個節點的代碼部分:

//deleting node here
age* temp = head;
temp->next->next;//!=NULL
temp = temp->next;
//temp->next = NULL;
delete temp;
#include<iostream>
using namespace std;

struct age{
    int a;
    age *next;
};

age *head,*current,*node1,*node2,*ona;

int main(){
    //creating a first node
    age *node1=new age();
    head=node1;
    node1->a=10;
    
    //creating a second node
    age *node2=new age();
    node2->a=20;
    //link nodes
    node1->next=node2;
    node2->next=NULL;
    
    //insertion of node ona between node 1 and node 2
    ona=new age;
    ona->a=15;
    ona->next=node1->next;
    node1->next=ona;
    
    //deleting node here
    age* temp = head;
    temp->next->next;//!=NULL
    temp = temp->next;
    //temp->next = NULL;
    delete temp;
    
    //displaying the otput
    current=head;
    while(current!=NULL){
        cout<<current->a<<endl;
        current=current->next;
    }
}

我建議看看這里:

對於普通 C 開發: https://www.learn-c.org/en/Linked_lists

在這個站點上,解釋了處理鏈表的所有標准方法,您可以找到每個操作的代碼片段。

對於 CPP 開發: https://www.codesdope.com/blog/article/c-deletion-of-a-given-node-from-a-linked-list-in-c/

在此站點上,您可以找到以 CPP OOP 樣式編碼的示例。

我稍微更改了 C 示例以適合您的代碼示例:

void remove_last(age * head) {
/* if there is only one item in the list, remove it */
if (head->next == NULL) {
    delete head;
    head = NULL;
    return;
}

/* get to the second to last node in the list */
node_t * current = head;
while (current->next->next != NULL) {
    current = current->next;
}

/* now current points to the second to last item of the list, so let's remove current->next */
delete(current->next);
current->next = NULL;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM