Thursday, October 13, 2016

Program to delete all the negative numbers from a queue without changing the order of other elements (using linked list)

#include<bits/stdc++.h>
using namespace std;

struct node
{
    int data;
    struct node *next;
}*node;

struct head
{
    int count;
    struct node *front;
    struct node *rear;
}*head;

void create_head()
{
    head=(struct head*) malloc (sizeof(struct head));
    head->count=0;
    head->front=NULL;
    head->rear=NULL;
}

void create_node()
{
    node=(struct node*) malloc (sizeof(struct node));
    node->next=NULL;
}

void enqueue(int data)
{
    create_node();
    node->data=data;

    if(head->count==0)
    {
        head->front=node;
        head->rear=node;
    }
    else
    {
        head->rear->next=node;
        head->rear=node;
    }

    head->count++;
}

void dequeue(struct node *temp)
{
    struct node *temp1;

    temp1=temp->next;
    temp->next=temp1->next;
    free(temp1);
    temp=temp->next;
    head->count--;
}

void main_process()
{
    struct node *temp;

    temp=head->front;

    while(temp->next!=NULL)
    {
        if(temp->next->data<0)
        {
            dequeue(temp);
        }
        else
        {
            temp=temp->next;

        }

    }
}

void print()
{
    struct node *temp;
    temp=head->front;

    while(temp!=NULL)
    {
        cout<<temp->data<<" ";
        temp=temp->next;
    }
    cout<<"\ntotal number of data : "<<head->count<<endl;
}

int main()
{
    create_head();
    enqueue(65);
    enqueue(54);
    enqueue(-3);
    enqueue(8);
    enqueue(-7);
    enqueue(43);
    enqueue(-98);
    enqueue(14);
    enqueue(65);
    enqueue(-76);
    cout<<"\nBefore desired operation : ";
    print();
    cout<<endl;
    main_process();
    cout<<"After desired operation : ";
    print();
    cout<<endl;
    return 0;
}

No comments:

Post a Comment