Deleting Nth node from end in Singly Linked list.

#include<bits/stdc++.h>
using namespace std;
struct node
{
    int data;
    struct node * next;
};
struct node * newnode, *temp, *temp2, *del_ptr;
struct node * create()
{
    struct node *head=0;
    int choice=1;
    while(choice==1)
    {
        newnode=(struct node*)malloc(sizeof(struct node));
        cout<<"Enter data ";
        cin>>newnode->data;
        newnode->next=0;
        if(head==0)
        head=temp=newnode;
        else
        {
            temp->next=newnode;
            temp=newnode;
        }
        cout<<"Want another node to be inserted : ";
        cin>>choice;
    }
    return head;
}
struct node * del_pos(struct node * head)
{
    int pos,i=0;
    cout<<"\nEnter the position from the end for deletion : ";
    cin>>pos;
    temp=head;
    while(i<pos && temp!=0)
    {
        temp=temp->next;
        i++;
    }
    if(i!=pos)
    cout<<"NOT! Possible\n";
    else
    {
        if(temp==0)
        {
            //in case the nth node from end is first node;
            temp2=head;
            head=head->next;
            free(temp2);
        }
        else
        {
            //in case the Nth node from end in not first node;
            temp2=head;
            while(temp->next!=0)
            {
                temp2=temp2->next;
                temp=temp->next;
            }
            del_ptr=temp2->next;
            temp2->next=temp2->next->next;
            free(del_ptr);
        }
    }
    return head;
}
void listprint(struct node *head)
{
    if(head==0)
        cout<<"\nList Empty!\n";
    else
    {
        temp=head;
        while(temp!=0)
        {
            cout<<temp->data<<" ";
            temp=temp->next;
        }
    }
}
int main()
{
    int choice=1;
    struct node*head=0;
    head=create();
    cout<<"The list is : ";
    listprint(head);
    //deleting nth nodes from end.
    while(choice==1)
    {
       if(head==0)
            {cout<<"List empty"; choice=0;}
       else
       {
            head=del_pos(head);
            cout<<"\nThe new list is :";
            listprint(head);
            cout<<"\nWant another node to be deleted";
            cin>>choice;
       }
    }
}

Comments

Popular posts from this blog

First_Come_First_Serve CPU Scheduling

Reversing stack Method 2 !! (One Helper Stack only)

Populating Next Right Pointers in Each Node in O(1) space (without queue and level order)

Calculate factorial of large numbers !! (Using Arrays)

Multiplication of large numbers (Given in string format)

Left View of Binary Tree (Method 1 using recursion)

Check Bracket Sequence

Image Multiplication

Boundary Traversal of binary tree

BST to greater sum tree