Static stack operations in C - c

i'm trying to perform all operations(push, pop, peep, update, show) on stack using array in C.It's working fine when i am calling the show() at last after calling all of the functions that i need. But whenever i call show() before any of the operations than it is not giving me the appropiate result.
I'm using following code:
int main()
{
push(1);
push(2);
push(3);
push(4);
push(6);
pop();
push(5);
show();//line 8
//push(7);//line 9
//pop();
//peep();
//update();
//show();//line 13
return;
}
void push(int num){//insert an item
if(top==MAXSIZE-1)
{
printf("Overflow condition");
return;
}
top++;
stack[top]=num;
//return;
}
void pop()//delete a item from top
{
int num;
if(top==-1)
{
printf("Underflow condition");
return;
}
num=stack[top];
top--;
//return;
}
void show()//display elements
{
if(top==-1){
printf("Underflow");
return;
}
while(top!=-1){
printf("%d\n",stack[top--]);
}
//return;
}
void peep()//extract information
{
int loc,num;
printf("enter location:\n");
scanf("%d",&loc);
if(top-loc+1 < 0)
{
printf("No item at the given location\n");
return;
}
else{
num=stack[top-loc+1];
printf("\nItem at location %d is %d",loc,num);
}
}
void update(){//update information
int loc,item;
printf("enter new item:");
scanf("%d",&item);
printf("enter location:");
scanf("%d",&loc);
if(top-loc+1 < 0)
{
printf("No item at the given location\n");
return;
}
else{
stack[top-loc+1]=item;
printf("\nItem inserted");
}
}
Here after calling show(),top will point to -1(empty) at line 8,so after that following consequences will be:
push() will insert at position 1 instead of at top.
pop() will show underflow condition.
peep() and update will go in if condition.
So how can i set top to the top element in the stack after once calling the show()?
Thanks.

Your show() method modifies the top pointer and this is wrong:
void show()//display elements
{
if(top==-1){
printf("Underflow");
return;
}
while(top!=-1){
printf("%d\n",stack[top--]); // <--- here 'top--' will modify the top pointer
}
//return;
}
You can change the show() method like this:
void show()//display elements
{
if(top==-1){
printf("Underflow");
return;
}
int i = top; // introducing a new variable to iterate through the stack
while(i!=-1){
printf("%d\n",stack[i--]); // now 'i' is modified
}
//return;
}

One problem with your show function is that, it is also trying to pop out all the data. You should not be doing the top-- in your show function.

//WAP to perform Stack Operation usin C--
1. Push, 2.pop, 3.peep, 4.change, 5.top-of-stack, 6.is-empty, 7.is-full, 8.display
#include<stdlib.h>
#include<stdio.h>
#define max_size 5
int stack[max_size],top=-1,i,x;
/*------ Function Prototype------------*/
void push();
void pop();
void peep();
void display();
void top_stack();
void change();
void is_empty();
/*-------------------------------------*/
int main()
{
int choice;
do{
printf("\n\n--------STACK OPERATIONS-----------\n");
printf("1.Push\n");
printf("2.Pop\n");
printf("3.Peep\n");
printf("4.Display\n");
printf("5.Change\n");
printf("6.TOP\n");
printf("7.exit\n");
printf("-----------------------");
printf("\nEnter your choice:\t");
scanf("%d",&choice);
switch(choice)
{
case 1: push();
break;
case 2: pop();
break;
case 3: peep();
break;
case 4: display();
break;
case 5: change();
break;
case 6: top_stack();
break;
case 7: exit(0);
break;
default: printf("\nInvalid choice:\n");
break;
}
}while(choice!=7);
return 0;
}
void push() //Inserting element in to the stack
{
int item;
if(top==(max_size-1))
{
printf("\nStack Overflow:");
}
else
{
printf("Enter the element to be inserted:\t");
scanf("%d",&item);
top=top+1;
stack[top]=item;
}
}
void pop() //deleting an element from the stack
{
int item;
if(top==-1)
{
printf("Stack Underflow:");
}
else
{
item=stack[top];
top=top-1;
printf("\nThe poped element: %d\t",item);
}
}
void peep()
{
printf("enter the i th element");
scanf("%d",&i);
if(top-i+1<0)
{
printf("\nStack is empty:");
}
else
{
printf("The topmost element of the stack is %d",stack[top-i+1]);
}
}
void display()
{
int i;
if(top==-1)
{
printf("\nStack is Empty:");
}
else
{
printf("\nThe stack elements are:\n" );
for(i=top;i>=0;i--)
{
printf("%d\n",stack[i]);
}
}
}
void change()
{
printf("enter the i th element");
scanf("%d",&i);
if(top-i+1<0)
{
printf("\nStack is empty:");
}
else
{
printf("enter the element to be changed\n");
scanf("%d",&x);
stack[top-i+1]=x ;
printf("The topmost element of the stack is %d",stack[top-i+1]);
}
}
void top_stack()
{
int t;
t=stack[top];
printf("The Topmost element of stack is =%d",t);
}

Related

Unexpected behaiviour, when trying to enter a new element in a linked List

So, I have to read a linked list from a binary file and then add new elements to it. It reads from the binary as expected, but when I try to add new elements to the list, it adds only the last one, which I enter.
Here is the code in main() responsible for reading, creating and inserting a new element into the List
int main()
{
int choice=0;
int confirmation=0;
t_Node *temp_node1, *temp_node2, *temphead;
unsigned int ID1, ID2;
FILE *fp;
fp = fopen("Data.bin","rb");
if(fp==NULL)
{
printf("File error");
exit(6);
}
while(1)
{
if(feof(fp))
{
break;
}
if (head == NULL)
{
head = readNode(fp);
temphead = head;
}else
{
temphead = readlist(temphead, fp);
}
}
fclose(fp);
while(1)
{
printf("\n\n");
printf("Hello world!\n\n 1-Enter a new element/s.\n 2-Copy data from one element to another (by ID).\n 3-Switch data between two elements (by ID).\n 4-Delete an element (by ID)\n 5-Print all elements\n 6-Delete all elements\n 0-Exit\n");
scanf("%d",&choice);
if(choice==0)
{
system("cls");
delete_List(head);
printf("EXIT BY USER");
break;
}
switch(choice)
{
case 1:
system("cls");
int temp=0;
t_Node *temphead1, *searched1, *searched2;
do
{
temphead1=makelist(temphead);
printf("press 0 to stop, any other key to go on\n");
fflush(stdin);
scanf("%d",&temp);
}while (temp!=0);
break;
case 2:
system("cls");
confirmation=0;
ID1=0;
ID2=0;
do
{
do
{
printf("Enter ID of the element you want to copy\n");
scanf("%u",&ID1);
temp_node1=Find_By_Id(ID1);
}while( temp_node1==NULL);
printNode(temp_node1);
printf("\nAre you sure?\n 1 for yes, 0 for no\n");
scanf("%d",&confirmation);
}while (confirmation==0);
confirmation=0;
do{
do{
printf("Enter ID of the element you want to copy to\n");
scanf("%u",&ID2);
temp_node2=Find_By_Id(ID2);
}while(temp_node2==NULL);
printNode(temp_node2);
printf("\nAre you sure?\n 1 for yes, 0 for no\n");
scanf("%d",&confirmation);
}while (confirmation==0);
confirmation=0;
Copy_first_to_second(temp_node1, temp_node2);
break;
case 3:
system("cls");
ID1=0;
ID2=0;
do{
do{
printf("Enter ID of the first element you want to switch data with\n");
scanf("%u",&ID1);
temp_node1=Find_By_Id(ID1);
}while( temp_node1==NULL);
printNode(temp_node1);
printf("\nAre you sure?\n 1 for Yes, 0 for No\n");
scanf("%d",&confirmation);
} while (confirmation==0);
confirmation=0;
do
{
do
{
printf("Enter ID of the second element you want to switch data with\n");
scanf("%u",&ID2);
temp_node2=Find_By_Id(ID2);
} while( temp_node2==NULL);
printNode(temp_node2);
printf("\nAre you sure?\n 1 for yes, 0 for no\n");
scanf("%d",&confirmation);
}while(confirmation==0);
confirmation=0;
Copy_first_to_second(temp_node1, temp_node2);
break;
case 4:
system("cls");
ID1=0;
do
{
do
{
printf("Enter ID of the element you want to delete\n");
scanf("%u",&ID1);
temp_node1=Find_By_Id(ID1);
} while( temp_node1==NULL);
printNode(temp_node1);
printf("\nAre you sure?\n 1 for yes, 0 for no\n");
scanf("%d",&confirmation);
}while (confirmation==0);
confirmation=0;
Delete_Element(temp_node1);
break;
case 5:
system("cls");
if (head==NULL)
{
printf("\nEnter elements first");
break;
}
printlist(head);
break;
case 6:
system("cls");
delete_List(head);
printf("List deleted");
break;
default:
delete_List(head);
exit(1);
}
}
return 0;
}
The structures:
typedef struct something
{
char name[50];
double value;
unsigned int ID;
}t_Something;
typedef struct node
{
t_Something smth;
struct node *next;
}t_Node;
And the functions:
t_Something readElement (FILE *file)
{
t_Something t_Struct;
int check=0;
unsigned int t_ID;
fread(&t_Struct,sizeof(t_Struct),1,file);
do{
t_ID=t_Struct.ID;
check=checkID(t_ID);
if (check==1)
{
break;
}
}while(1);
return t_Struct;
}
t_Something addElement()
{
t_Something t_Struct;
int check=0;
unsigned int t_ID;
printf("\nInput name\t");
fflush(stdin);
gets(t_Struct.name);
printf("\nInput value\t");
fflush(stdin);
scanf("%0.2lf",&t_Struct.value);
printf("\nInput ID, must be unique\t");
fflush(stdin);
do
{
scanf("%u",&t_Struct.ID);
t_ID=t_Struct.ID;
check=checkID(t_ID);
if (check==1)
{
break;
}
}while (1);
return t_Struct;
}
t_Node* addNode (t_Node *temphead)
{
t_Node *pNode;
pNode = (t_Node*)malloc(sizeof(t_Node));
if (pNode==NULL)
{
printf("\nMemory error\n");
delete_List(head);
}
pNode->smth=addElement();
pNode->next=NULL;
return pNode;
}
t_Node* makelist(t_Node *temphead)
{
t_Node *temp2=addNode(temphead);
temphead->next=temp2;
return temp2;
}
t_Node* readNode (FILE *file)
{
t_Node *pNode;
pNode = (t_Node*)malloc(sizeof(t_Node));
if (pNode==NULL)
{
printf("\nMemory error\n");
delete_List(head);
}
pNode->smth=readElement(file);
pNode->next=NULL;
return pNode;
}
t_Node* readlist (t_Node *temphead, FILE *file)
{
t_Node *temp2=readNode(file);
temphead->next=temp2;
return temphead->next;
}
void printlist (t_Node* current){
for (;;){
printNode(current);
current=current->next;
if (current==NULL) break;
}
}
void printNode (t_Node* current)
{
printf("\n--------\n");
printf("name: %s\n", current->smth.name);
printf("value: %lf", current->smth.value);
printf("\nID: %u\n", current->smth.ID);
}
void delete_List (t_Node* current)
{
t_Node *temp;
for (;;){
temp=current->next;
free(current);
current=temp;
if (current==NULL)
{
break;
}
}
}
int checkID (unsigned int number)
{
t_Node *current=head;
int pass=1;
if (head!=NULL)
{
for(;;)
{
if(current->smth.ID==number)
{
pass=0;
return pass;
}
current=current->next;
if (current==NULL)
{
break;
}
}
}
return pass;
}
t_Node* Find_By_Id (unsigned int searched)
{
t_Node* current=head;
for (;;)
{
if (searched==current->smth.ID)
{
return current;
}
current=current->next;
if (current==NULL)
{
break;
}
}
printf("\nThere is no element with this ID\n");
return NULL;
}
void Change_two_elements (t_Node* first, t_Node* second)
{
t_Something temp;
temp=first->smth;
first->smth=second->smth;
second->smth=temp;
}
void Copy_first_to_second (t_Node* first, t_Node* second)
{
second->smth=first->smth;
}
void Delete_Element (t_Node* element)
{
t_Node* temp;
if (element==head)
{
head=element->next;
free(element);
}else
{
for(temp=head;;)
{
if (temp->next==element)
{
break;
}
temp=temp->next;
}
temp->next=element->next;
free(element);
}
}
Sorry for the large amount of code, but otherwise it wouldn't be possible to see the full picture

Circular Queue Operations Using Array

Code shows basic operations on Circular Queue.
#define maxsize 10
typedef struct queue
{
int data[maxsize];
int f,r;
}myQueue;
myQueue q;
void init(myQueue *q);
int full(myQueue *q);
int empty(myQueue *q);
void enqueue(myQueue *q,int num);
void dequeue(myQueue *q);
void print(myQueue *q);
void main()
{
init(&q);
int op;
do
{
printf("\nCircular queue operations: Press:\n");
printf("1 for enqueue\n");
printf("2 for dequeue\n");
printf("3 to print Circular Queue\n");
int num,choice;
printf("\nEnter choice:\n");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("Enter number to insert :\n");
scanf("%d",&num);
if(full(&q))
{
printf("\nQueue is full\n");
exit(0);
}
enqueue(&q,num);
break;
case 2: if(empty(&q))
{
printf("\nQueue is empty\n");
exit(0);
}
dequeue(&q);
break;
case 3: printf("Printing current queue: \n");
print(&q);
break;
default:break;
}
printf("Press 1 to continue or 0 to exit:\n");
scanf("%d",&op);
}
while(op);
}
void init(myQueue *q)
{
q->f=-1;
q->r=-1;
}
int full(myQueue *q)
{
if((q->r+1)%maxsize==q->f)
{
return 1;
}
else
return 0;
}
int empty(myQueue *q)
{
if(q->r==-1)
{
return 1;
}
else
return 0;
}
enqueue function is used to add the elements into queue.
void enqueue(myQueue *q,int num)
{
if(empty(&q))
{
q->f=0;
q->r=0;
}
else
{
q->r=(q->r+1)%maxsize;
}
q->data[q->r]=num;
printf("\n%d is enqueued\n",q->data[q->r]);
}
Dequeue function is used to delete elements from the stack.
void dequeue(myQueue *q)
{
int del_num;
del_num=q->data[q->f];
if(q->f==q->r)
{
init(&q);
}
else
{ //To move front to the next position in the circular array.
q->f=(q->f+1)%maxsize;
}
printf("\n%d is dequeued\n",del_num);
}
void print(myQueue *q)
{
int i;
for(i=q->f;i!=q->r;i=(i+1)%maxsize)
{
printf("%d\n",q->data[i]);
}
printf("%d\n",q->data[q->r]);
}
Issue: Circular queue is automatically enqueuing the 0 element in it initially.
However, rest of the operations are working just fine.
I am not able to identify, why it is automatically inserting 0 in the circular queue, without me enqueuing it.
Your print() function always prints q->data[q->r] as its last operation. This makes no sense when your queue is empty. Maybe you can avoid it like this:
void print(myQueue *q)
{
if (empty(q))
return;
int i;
for(i=q->f;i!=q->r;i=(i+1)%maxsize)
{
printf("%d\n",q->data[i]);
}
printf("%d\n",q->data[q->r]);
}
Anyway there are many more problems with your code, which I doubt it is compiling correctly. Just as an example, the function enqueue() receives a parameter of type myQueue*. Then it provides function empty with the address of it, but this is wrong. you have to pass the function the pointer itself, so q instead of &q. The same mistake is repeated over and over again.
1st Code Snippet requiring change:
void enqueue(myQueue *q,int num)
{
The below line is changed.
if(empty(q)==1)
{
q->f=0;
q->r=0;
}
else
{
q->r=(q->r+1)%maxsize;
}
q->data[q->r]=num;
printf("\n%d is enqueued\n",q->data[q->r]);
}
2nd code snippet requiring changed:
void dequeue(myQueue *q)
{
int del_num;
del_num=q->data[q->f];
if(q->f==q->r)
{
Line below is changed.
init(q);
}
else
{ //To move front to the next position in the circular array.
q->f=(q->f+1)%maxsize;
}
printf("\n%d is dequeued\n",del_num);
}
3rd snippet requiring change:
void print(myQueue *q)
{
int i;
Line below is changed.
if(empty(q))
{
printf("Queue empty");
exit(0);
}
else
{
printf("Printing current queue: \n");
for(i=q->f;i!=q->r;i=(i+1)%maxsize)
{
printf("%d\n",q->data[i]);
}
printf("%d\n",q->data[q->r]);
}
}
That makes it perfectly alright. :)
#include <stdio.h>
#define SIZE 5
int items[SIZE];
int front = -1, rear = -1;
int isFull() {
if ((front == rear + 1) || (front == 0 && rear == SIZE - 1)) return 1;
return 0;
}
int isEmpty() {
if (front == -1) return 1;
return 0;
}
void enQueue(int element) {
if (isFull())
printf("\n Queue is full!! \n");
else {
if (front == -1) front = 0;
rear = (rear + 1) % SIZE;
items[rear] = element;
printf("\n Inserted -> %d", element);
}
}
int deQueue() {
int element;
if (isEmpty()) {
printf("\n Queue is empty !! \n");
return (-1);
} else {
element = items[front];
if (front == rear) {
front = -1;
rear = -1;
}
else {
front = (front + 1) % SIZE;
}
printf("\n Deleted element -> %d \n", element);
return (element);
}
}
void display() {
int i;
if (isEmpty())
printf(" \n Empty Queue\n");
else {
printf("\n Front -> %d ", front);
printf("\n Items -> ");
for (i = front; i != rear; i = (i + 1) % SIZE) {
printf("%d ", items[i]);
}
printf("%d ", items[i]);
printf("\n Rear -> %d \n", rear);
}
}
int main() {
deQueue();
enQueue(1);
enQueue(2);
enQueue(3);
enQueue(4);
enQueue(5);
enQueue(6);
display();
deQueue();
display();
enQueue(7);
display();
enQueue(8);
return 0;
}

Segmenation Fault - Working on stack data structure

I'm attempting to create a program that would allow the user to create a stack data structure using the push, pop, and peek command. However, I keep running into a segmentation fault whenever I try and use the push command! I have no idea why it's not working, because I made sure to use malloc on the stack structure. The peek and pop command are working (as far as I can tell). Any help??
#include<stdlib.h>
#include<stdio.h>
#include "stack.h"
int mainMenuChoice, pushValue;
void mainMenu() {
printf("\nEnter your option: \n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Peek\n");
printf("4. Exit\n");
scanf("%d", &mainMenuChoice);
}
Stack * initializeStack() {
Stack *new_stack;
int capacity = 100;
new_stack = (Stack *)malloc(sizeof(Stack));
new_stack->items = (int *)malloc(sizeof(int)*capacity);
new_stack->size = 0;
return new_stack;
}
void push(Stack *new_stack, int item) {
new_stack->items[new_stack->size++] = item;
}
void pop(Stack *new_stack) {
if(new_stack->size == 0) {
printf("The stack is empty, you can't pop any items!\n");
} else {
new_stack->size--;
}
}
int peek(Stack *new_stack) {
if(new_stack->size == 0) {
printf("The stack is empty.\n");
} else {
return new_stack->items[new_stack->size-1];
}
}
void menuOptions(int option) {
Stack *new_stack = initializeStack();
if(option == 1) {
Stack *new_stack;
printf("Enter an element to push: ");
scanf("%d", &pushValue);
push(new_stack, pushValue);
mainMenu();
menuOptions(mainMenuChoice);
} else if(option == 2) {
pop(new_stack);
mainMenu();
menuOptions(mainMenuChoice);
} else if(option == 3) {
peek(new_stack);
mainMenu();
menuOptions(mainMenuChoice);
} else if(option == 4) {
printf("Exiting...\n");
exit(0);
} else {
printf("Invalid input, please try again!\n");
mainMenu();
menuOptions(mainMenuChoice);
}
}
void program() {
mainMenu();
menuOptions(mainMenuChoice);
}
Also, this is the how I've structured the stack:
typedef struct Stack {
int size;
int *items;
}Stack;
Thank you so much in advance, I appreciate it!
I've simplified things a bit. You were having too many recursive calls and new_stack was being redefined [but not reallocated]. You'll still have more work to do (e.g. peek returns a value, but pop does not)
Here's the code [please pardon the gratuitous style cleanup]:
#include <stdlib.h>
#include <stdio.h>
//#include "stack.h"
typedef struct Stack {
int size;
int *items;
} Stack;
int mainMenuChoice;
int pushValue;
Stack *top_stack;
void
mainMenu()
{
printf("\nEnter your option: \n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Peek\n");
printf("4. Exit\n");
scanf("%d", &mainMenuChoice);
}
Stack *
initializeStack()
{
Stack *new_stack;
int capacity = 100;
new_stack = (Stack *) malloc(sizeof(Stack));
new_stack->items = (int *) malloc(sizeof(int) * capacity);
new_stack->size = 0;
return new_stack;
}
void
push(Stack *new_stack, int item)
{
new_stack->items[new_stack->size++] = item;
}
void
pop(Stack *new_stack)
{
if (new_stack->size == 0) {
printf("The stack is empty, you can't pop any items!\n");
}
else {
new_stack->size--;
}
}
int
peek(Stack *new_stack)
{
if (new_stack->size == 0) {
printf("The stack is empty.\n");
return -1;
}
else {
return new_stack->items[new_stack->size - 1];
}
}
void
menuOptions(Stack *new_stack,int option)
{
if (option == 1) {
printf("Enter an element to push: ");
scanf("%d", &pushValue);
push(new_stack, pushValue);
}
else if (option == 2) {
pop(new_stack);
}
else if (option == 3) {
peek(new_stack);
}
else if (option == 4) {
printf("Exiting...\n");
exit(0);
}
else {
printf("Invalid input, please try again!\n");
}
}
int
main()
{
top_stack = initializeStack();
while (1) {
mainMenu();
menuOptions(top_stack,mainMenuChoice);
}
return 0;
}

My Circular Queue implementation is not working properly

I have created a program to implement a Circular Queue with insert, delete and display. The insertion is working fine and the deletion too but once I try to enter numbers after deletion, nothing is displayed. Here is my source code:
#include<stdio.h>
#include<conio.h>
#define SIZE 5
int front = -1;
int rear = -1;
int queue[SIZE];
void enqueue(int item);
int dequeue();
void display();
void main()
{
int item, choice, cont = 1;
clrscr();
while(cont == 1)
{
printf("\n1.Enqueue into queue.\n");
printf("\n2.Dequeue from queue.\n");
printf("\n3.display quesue elements\n");
printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter the value of item: ");
scanf("%d",&item);
enqueue(item);
break;
case 2:
item = dequeue();
if(item != NULL)
{
printf("\nItem dequeued: %d\n",item);
}
break;
case 3:
display();
break;
default:
printf("\nInvalid choice.\n");
break;
}
printf("\nDo you want to continue (1/0): ");
scanf("%d",&cont);
}
getch();
}
void enqueue(int item)
{
if(front==0 && rear==SIZE-1)
printf("\n Queue OverFlow Occured");
else if(front==-1 && rear==-1)
{
front=rear=0;
queue[rear]=item;
}
else if(rear==SIZE-1 && front!=0)
{
rear=0;
queue[rear]=item;
}
else
{
rear++;
queue[rear]=item;
}
}
int dequeue()
{
int item = NULL;
if(front == -1 && rear == -1)
{
printf("\nQueue is empty. Dequeue not possible.\n");
}
else
{
item = queue[front];
queue[front] = NULL;
if(front == rear)
{
front = -1;
rear = -1;
}
else
{
front = front + 1;
}
}
return(item);
}
void display()
{
int i;
if(front==-1)
printf("\n No elements to display");
else
{
printf("\n The queue elements are:\n ");
for(i=front;i<=rear;i++)
{
printf("\t %d",queue[i]);
}
}
}
Check this code its working fine.
Few suggestions don't use conio.h [clrscr(), and getch()] these are not standards.
Try the code below it worked for me fine.
CODE
#include<stdio.h>
#define SIZE 5
int front = -1;
int rear = -1;
int queue[SIZE];
void enqueue(int item);
int dequeue();
void display();
int main()
{
int item, choice, cont = 1;
while(cont == 1)
{
printf("\n1.Enqueue into queue.\n");
printf("\n2.Dequeue from queue.\n");
printf("\n3.display quesue elements\n");
printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter the value of item: ");
scanf("%d",&item);
enqueue(item);
break;
case 2:
item = dequeue();
if(item != NULL)
{
printf("\nItem dequeued: %d\n",item);
}
break;
case 3:
display();
break;
default:
printf("\nInvalid choice.\n");
break;
}
printf("\nDo you want to continue (1/0): ");
scanf("%d",&cont);
}
printf("");
return 0;
}
void enqueue(int item)
{
if(front==0 && rear==SIZE-1)
printf("\n Queue OverFlow Occured");
else if(front==-1 && rear==-1)
{
front=rear=0;
queue[rear]=item;
}
else if(rear==SIZE-1 && front!=0)
{
rear=0;
queue[rear]=item;
}
else
{
rear++;
queue[rear]=item;
}
}
int dequeue()
{
int item = NULL;
if(front == -1 && rear == -1)
{
printf("\nQueue is empty. Dequeue not possible.\n");
}
else
{
item = queue[front];
queue[front] = NULL;
if(front == rear)
{
front = -1;
rear = -1;
}
else
{
front = front + 1;
}
}
return(item);
}
void display()
{
int i;
if(front==-1)
printf("\n No elements to display");
else
{
printf("\n The queue elements are:\n ");
for(i=front;i<=rear;i++)
{
printf("\t %d",queue[i]);
}
}
}
OUTPUT
Do you want to continue (1/0): 1
1.Enqueue into queue.
2.Dequeue from queue.
3.display quesue elements
Enter your choice: 3
The queue elements are:
5 5
Do you want to continue (1/0): 1
1.Enqueue into queue.
2.Dequeue from queue.
3.display quesue elements
Enter your choice: 1
Enter the value of item: 43
Do you want to continue (1/0): 1
1.Enqueue into queue.
2.Dequeue from queue.
3.display quesue elements
Enter your choice: 3
The queue elements are:
5 5 43
Do you want to continue (1/0): 1
1.Enqueue into queue.
2.Dequeue from queue.
3.display quesue elements
Enter your choice: 2
Item dequeued: 5
Do you want to continue (1/0): 1
1.Enqueue into queue.
2.Dequeue from queue.
3.display quesue elements
Enter your choice: 3
The queue elements are:
5 43
Do you want to continue (1/0):
Thats a rather confusing code. Since the idea is for the queue to be circular, trying to determine if the queue is full by checking the position of front and rear can be really tricky, aswell as trying to make decisions based on front being higher than rear etc. You can avoid all that. A third variable keeping track of the length of the queue will make your life a whole lot easier.
Try this implementation instead:
#define SIZE 5
int queue[SIZE];
int read = 0, write = 0, size = 0;
void enqueue(int item)
{
if (size >= SIZE)
{
printf("Queue is full");
return;
}
queue[write] = item;
write = (write + 1) % SIZE;
size++;
}
int dequeue()
{
if (size == 0)
{
printf("Queue is empty");
return 0;
}
read %= SIZE;
size--;
return queue[read++];
}
Here is your Fully Functional updated code. I pasted code on Ideone.com Link is link to code
If you don't understand anything just ask. I tried to explain it using comments. And now it is not having any problem that you were facing .
#include<stdio.h>
#include<conio.h>
#define SIZE 5
int front = -1;
int rear = -1;
int queue[SIZE];
void enqueue(int item);
int dequeue();
void display();
void main()
{
int item, choice, cont = 1;
clrscr();
while(cont == 1)
{
printf("\n1.Enqueue into queue.\n");
printf("\n2.Dequeue from queue.\n");
printf("\n3.display quesue elements\n");
printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter the value of item: ");
scanf("%d",&item);
enqueue(item);
break;
case 2:
item = dequeue();
if(item != NULL)
{
printf("\nItem dequeued: %d\n",item);
}
break;
case 3:
display();
break;
default:
printf("\nInvalid choice.\n");
break;
}
printf("\nDo you want to continue (1/0): ");
scanf("%d",&cont);
}
getch();
}
void enqueue(int item)
{
int temp = (rear+1)%SIZE; //EDIT HERE
if(temp == front){
printf("\n Queue OverFlow Occured");
return;
}
else if(front==-1 )
{
front=rear=0;
queue[rear]=item;
return;
}
else{
rear = (rear+1)%SIZE; // EDIT HERE
queue[rear%SIZE]=item;
}
}
int dequeue()
{
int item = NULL;
if(front == rear) // modified condition
{
printf("\nQueue is empty. Dequeue not possible.\n");
}
else
{
item = queue[front];
queue[front] = NULL;
front++; // front must be incremented
if(front > rear)
{
front = -1;
rear = -1;
}
}
return(item);
}
void display()
{
int i;
if(front==-1)
printf("\n No elements to display");
else
{
printf("\n The queue elements are:\n ");
for(i=front;i<=rear;i++)
{
printf("%d\t",queue[i]);
}
}
}

infix to postfix using stack error in updating top variable

I'm trying to implement a code for infix to postfix conversion but I'm not able to obtain the output. By analyzing the program I found that the variable top s not getting updated even though I'm returning its value back to the main. Please help me figure it out. The code is:
#include<stdio.h>
char stack[15];
int check(char op)
{
int rank=0;
switch(op)
{
case '/':
rank=1;
break;
case '*':
rank=2;
break;
case '+':
rank=3;
break;
case '-':
rank=4;
break;
}
return rank;
}
int POP(char stack[15],int top)
{
if(top==-1)
{
printf("Stack Underflow");
return top;
}
else
{
top--;
printf("%c",stack[top+1]);
return top;
}
}
int PUSH(char stack[15],int top,char op)
{
char opstack;
int rank1,rank2;
if(top>=14)
{
printf("Stack Overflow");
return top;
}
else
{
if(top==-1)
{
top++;
stack[top]=op;
return top;
}
else
{
opstack=stack[top];
rank1=check(op);
rank2=check(opstack);
if( rank1 <= rank2 )
{
top++;
stack[top]=op;
}
else
{
top=POP(stack,top);
top=PUSH(stack,top,op);
}
return top;
}
}
}
int main()
{
char string[15],ch;
int top=-1,i;
printf("Enter the infix operation: ");
gets(string);
fflush(stdin);
for(i=0;string[i]!='\0';i++)
{
ch=string[i];
if( ((ch>='a') && (ch<='z'))||((ch>='A') &&(ch<='Z')) )
{
printf("%c",string[i]);
}
else
{
ch=string[i];
top=PUSH(stack,top,ch);
}
top=POP(stack,top);
}
return 0;
}
in main function add these three lines after for loop End.and remove top=POP(stack,top);
inside for loop.
while(top!=-1)
top=POP(stack,top);
printf("\n");
modified main function:
int main()
{
char string[15],ch;
int top=-1,i;
printf("Enter the infix operation: ");
gets(string);
fflush(stdin);
for(i=0;string[i]!='\0';i++)
{
ch=string[i];
if( ((ch>='a') && (ch<='z'))||((ch>='A') &&(ch<='Z')) )
{
printf("%c",string[i]);
}
else
{
ch=string[i];
top=PUSH(stack,top,ch);
}
}
while(top!=-1)
top=POP(stack,top);
printf("\n");
return 0;
}

Resources