C++链表节点

mzmfm0qo  于 2023-01-28  发布在  其他
关注(0)|答案(1)|浏览(250)

我对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;
    }
}
vsnjm48y

vsnjm48y1#

我建议看一下这里:
对于普通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;
}

相关问题