Home > Enterprise >  C linked list nodes
C linked list nodes

Time:01-25

I have very basic concepts of linked list with C . Here I have nodes linked, but the idea is to delete the last node, how do I achieve this?

This is the portion of code aimed to delete the last node:

//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;
    }
}

CodePudding user response:

To delete the last node, you need to traverse the linked list until you reach the second to last node, and then update its next pointer to point to NULL instead of the last node. Here's an example of how you can do this:

age* temp = head;
while (temp->next->next != NULL) {
    temp = temp->next;
}
delete temp->next;
temp->next = NULL;

This will delete the last node of the linked list and set the next pointer of the second to last node to NULL.

CodePudding user response:

I suggest to have a look here:

For plain C development: https://www.learn-c.org/en/Linked_lists

On this site all standard methods for handling linked lists are explained and you can find code snippets for every operation.

For CPP development: https://www.codesdope.com/blog/article/c-deletion-of-a-given-node-from-a-linked-list-in-c/

On this site you can find an example coded in CPP OOP style.

I change the C example a little bit to fit your code example:

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;
}
  • Related