C Program to delete an element from last position (last element) of a given SLL | C Program

 delete from last position (last element) | SLL |  C Program

#include<stdio.h>

#include<stdlib.h>

struct node
{
    int data;
    struct node *next;
};
struct node *start=NULL;

main()
{
    int i,value,ne;  // ne=Number of element in list, pos= position
    struct node *n,*temp,*del;

    n=malloc(sizeof(struct node));

    printf("\n\n\tHow many value do you want to Enter in List: ");
    scanf("%d",&ne);

    printf("\nEnter first data for list: ");
    scanf("%d",&value);

    n->data=value;
    n->next=NULL;
    start=n;

    for(i=2;i<=ne;i++)
    {
        n=malloc(sizeof(struct node));

        printf("Enter next data: ");
        scanf("%d",&value);

        n->data=value;
        n->next=NULL;
        temp=start;

        while(temp->next!=NULL)
            temp=temp->next;

        temp->next=n;
    }

    if(start==NULL)   // for display
        printf("\n\t** List is empty **");

    else
    {
        temp=start;

        printf("\n\tData in the List: ");

        while(temp!=NULL)
        {
            printf("%d\t",temp->data);
            temp=temp->next;
        }
    }
    //for Deleting at last position
    temp=start;
    while(temp->next->next!=NULL)
        temp=temp->next;
    del=temp->next;
    temp->next=NULL;
    free(del);

    if(start==NULL)   // for display
        printf("\n\t** List is empty **");

    else
    {
        temp=start;

        printf("\n\n\t** Last element deleted successfully **");
        printf("\n\n\tUpdated List:  ");

        while(temp!=NULL)
        {
            printf("%d\t",temp->data);
            temp=temp->next;
        }
    }
    getch();
}

OUTPUT:


Post a Comment

0 Comments