Question:
Exercise 7:
Delete all Negative Integer
Write a program that will take a queue of integers and deletes all negative integers without changing the order of the remaining elements in queue.
Input Data Output Data
Q: 1 2 -3 4 - 5 Q: 1 2 4
Soultion:
#include <stdio.h>
#include <stdlib.h>
#include<process.h>
#include<limits.h>
struct node
{
int item;
struct node *nextNode;
};
void enqueue(struct node *front, struct node *rear, int data)
{
struct node *newNode;
newNode -> nextNode = NULL;
newNode -> item = data;
if(front == NULL & rear == NULL)
{
front = rear = newNode;
return;
}
rear -> nextNode = newNode;
rear = newNode;
}
void dequeue(struct node *front, struct node *rear)
{
struct node *temp;
if(front && front -> nexNode != NULL)
{
temp = front;
front = front -> nextNode;
delete(temp);
}
else if(front == back)
{
delete(front);
rear = NULL;
}
else
{
printf("\nThe queue is empty\n");
}
}
void traverse (struct node *head)
{
while(head != NULL)
{
printf(head -> item);
head = head -> nextNode;
}
}
void traverseSorted(struct node *head, struct node *rear)
{
struct node *nodeNext = head -> nextNode;
struct node * prevNode = rear;
while(head != prevNode -> nextNode)
{
if(head -> item < 0)
{
nodeNext = nodeNext -> nextNode;
dequeue(head, rear);
}
else
{
nodeNext = nodeNext -> nextNode;
enqueue(head, rear, head -> item);
dequeue(head, rear);
}
}
}
int main()
{
struct node *front = NULL;
struct node *rear = NULL;
enqueue(front, rear, 1);
enqueue(front, rear, -2);
enqueue(front, rear, 5);
enqueue(front, rear, -9);
enqueue(front, rear, -2);
enqueue(front, rear, 10);
traverseSorted(front, rear);
traverse(front);
return 0;
}