Monday, 29 December 2014

Delete alternate elements of a linked-list

This code is written in c++ . This code deletes all the alternate nodes of the linked-list starting from the head . We have used the create function to create the nodes of the linked-list and display function to display the elements of the linked-list . Let's talk about the delete_alternate function , this function has been employed to delete the alternate nodes of the linked-list . We have used two pointers both pointing to the head of the list (pptr and ptr) . ptr points to a node at a time whereas pptr points to the previous node of ptr as assigned by the code snippet :--

pptr=ptr;
 ptr=ptr->link; 

We have used a counter which counts the position of node in traversal order , starting from the head . Assigning position 1 to the head we have deleted all the nodes lying at even positions and pointing to the next nodes whenever the node has an odd position . The deletion logic is given in the else clause of the while loop .

else
        {
            pptr->link=ptr->link;
            ptr=ptr->link;
        }

Input List:      8->7->6->5->4->3->2->1

Output List:   8->6->4->2

Code:--

#include<iostream>
#include<conio.h>
using namespace std;

// structure to define single node of the list
struct node
{
    int data;
    node *link;
}*head=NULL,*ptr,*pptr;

// function to create nodes of the list
void create()
{
    int item;
    cout<<"enter the item you want to insert in the list"<<endl;
    cin>>item;
    if(head==NULL)
    {
        ptr=new node;
        ptr->data=item;
        ptr->link=NULL;
        head=ptr;
    }
    else
    {
        ptr=new node;
        ptr->data=item;
        ptr->link=head;
        head=ptr;
    }
}

// function to traverse the list and display the elements
void display()
{
    ptr=head;
    while(ptr!=NULL)
    {
        cout<<ptr->data<<"\t";
        ptr=ptr->link;
    }
}

// function to delete alternative nodes
void delete_alternate()
{
    pptr=head;
    ptr=head;
    int counter=0;
    while(ptr!=NULL)
    {
        counter++;
        if(counter%2==1)
        {
            pptr=ptr;
            ptr=ptr->link;
        }
        else
        {
            pptr->link=ptr->link;
            ptr=ptr->link;
        }
    }
    display();
}

// main method
int main()
{
    int option;
    while(option!=4)
    {
        cout<<endl;
        cout<<"enter 1. to enter the element in the list"<<endl;
        cout<<"enter 2. to display the list"<<endl;
        cout<<"enter 3. to delete alternative elements from the linked-list"<<endl;
        cout<<"enter 4. to exit"<<endl;
        cin>>option;
        switch(option)
        {
            case 1: create();
            break;
            case 2: display();
            break;
            case 3: delete_alternate();
            break;
        }
    }
    getch();
    return 0;
}

2 comments: