C Programming Examples on Stacks & Queues

//Stacks #include<stdio.h> void main() { int data[5],top=0; int ch,i=1,stack=4; int temp=0; while(ch!=4) { printf("Size of Stack[%d]\n",stack); printf("\n1. Push : "); printf("\n2. Pop : "); printf("\n3. Display : "); printf("\nEnter Your Choice : "); scanf("%d",&ch); system("cls"); switch(ch) { case 1 : if(top==4) { printf("Stack is full\n"); } else { printf("\n\n Enter Data %d :",i); scanf("%d",&temp); system("cls"); data[++top]=temp; i++; stack--; } break; case 2 : if(top==0) { printf("Stack is empty\n"); stack=4; i=1; } else { printf("Pop Element : %d\n",data[top]); stack++; top--; } break; case 3 : if(top==0) { printf("Stack is empty\n"); stack=4; i=1; } else { printf("Array is : "); for(i=1;i<=top;i++) { printf("%d",data[i]); } printf("\n"); } break; default : printf("\n Not a good choice\n"); break; } } } //Queue #include<stdio.h> main() { int ch,i; int queue[2]; int queue_size=3; int queue_count=3; int front=0,rear=-1; int temp =0; while(ch!=4) { printf("Size of Queue[%d]\n\n",queue_count); printf("1.Insert\n"); printf("2.Delete\n"); printf("3.Display\n"); printf("Enter Your Choice : "); scanf("%d",&ch); switch(ch) { case 1 : { if(rear==queue_size-1) { system("cls"); printf("Queue is full\n"); } else { printf("Enter data to Queue : "); scanf("%d",&temp); ++rear; queue[rear]= temp; queue_count--; system("cls"); } } break; case 2 : { if(front>rear) { system("cls"); printf("Queue is Empty\n"); } else { system("cls"); printf("Delete %d\n",queue[front]); front++; queue_count++; } } break; case 3 : { if(front>rear) { system("cls"); printf("Queue is Empty\n"); } else { system("cls"); printf("Array is : "); for(i=front; i<=rear; i++) { printf("%d",queue[i]); } printf("\n"); } } break; default : printf("No choice\n "); } } }

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.