Sunday, January 15, 2023

Singly Linked List Delete Last Node

Singly Linked List Delete At Last or Remove Last Node Function

Function Delete Last Node in Singly Linked List:
void delete_last()
{
    struct node *a,*b=head;
    while(b->next!=NULL)
    {
        a=b;
        b=b->next;
    }
    a->next=NULL;
    free(b);
    b=NULL;
}

Full Program:
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *next;
};
struct node *newnode,*head,*temp;

void create()
{int num,i;
printf("\nHow many nodes you want to create:");
scanf("%d",&num);
for(i=0; i<num; i++)
{
newnode=(struct node *)malloc(sizeof(struct node));
printf("\nEnter Data:");
scanf("%d",&newnode->data);
newnode->next=NULL;
if(head==NULL)
{head=temp=newnode;}
else
{temp->next=newnode;
temp=temp->next;
}}}

void delete_last()
{
    struct node *a,*b=head;
    while(b->next!=NULL)
    {
        a=b;
        b=b->next;
    }
    a->next=NULL;
    free(b);
    b=NULL;
}
void display()
{
    struct node *p;
p=head;
while(p->next!=NULL)
{
printf("%d->", p->data);
p=p->next;
}
printf("%d->",p->data);
}
void main()
{
    create();
    display();
    delete_last();
    printf("\nAfter Deleting Last Node:")
    display();
    getch();
}
 
Output:


l

No comments: