Solved programming problem

Delete Alternate element from a single linked list in C++.

Source code

#include <iostream>

using namespace std;

struct list

{

    int data;

    struct list *next;

};

typedef struct list node;

node *head;

void insert_node()

{

    node *temp=new node();

    node *last;

    cout<<"data: ";

    cin>>temp->data;

    temp->next = NULL;

    if(head==NULL)

    {

        head= temp;

    }

    else

    {

        last = head;

        while(last->next != NULL)

        {

            last = last->next;

        }

        last ->next = temp;

    }

}

void  print_node()

{

    node *temp = head;

    if(head== NULL)

    {

        cout<<"
No Data Found "<<endl;

        return;

    }

    else

    {

        while(temp != NULL)

        {

            cout<<temp->data<< " ";

            temp = temp->next;

        }

    }

}

void alternative()

{

    node *temp=head,*prev=temp;

    int count =0;

    while(temp->next != NULL)

    {

        count++;

        if(count%2==0) ///find the even index

        {

             prev->next =temp->next; ///change previous address

             delete(temp);

        }

        prev = temp; ///save temp to prev

        temp = temp->next;

    }

}

int main()

{

    int flag;

    do

    {

        cout<<"Press 1 to Insert Node: ";

        cin>>flag;

        if(flag!=1) break;

        insert_node();

    }

    while(flag==1);

    cout<<"
Linked List:  " ;

    print_node();

    alternative();

    cout<<"
New Linked List:  " ;

    print_node();

    cout<<endl;

    return 0;

}

Output

Press 1 to Insert Node: 1
data: 54
Press 1 to Insert Node: 1
data: 7
Press 1 to Insert Node: 1
data: 4
Press 1 to Insert Node: 1
data: 9
Press 1 to Insert Node: 1
data: 3
Press 1 to Insert Node: 0

Linked List:  54 7 4 9 3
New Linked List:  54 4 3

Join the discussion

Add your comment