IDE-11 Data Structures
Department of Electrical Engineering
Stack (Array Implementation)
#include <stdio.h> //Defining the size of array # define SIZE 100 //Declaration of stack array and top variable using structures struct node { int stack[SIZE]; int top; }*s; typedef struct node NODE; //Function to push(add/insert) an element on the top of the stack void push(NODE *pu) { int item; //if stack is full(reached SIZE) if(pu->top == SIZE-1) { printf("\nThe stack is Full"); } //otherwise we can push new element else { printf("\nEnter the element to be pushed(inserted):"); scanf("%d",&item); pu->stack[++pu->top]=item; } } //Function to pop (delete/remove) an element from the top of the stack void pop(NODE *po) { int item; //if top pointer points to NULL=> stack is empty if(po->top == -1) printf("\nThe stack is empty"); M. Usman Aslam (
[email protected]) Lecturer , RCET Gujranwala 1/3
IDE-11 Data Structures //otherwise top most element can be popped else { item=po->stack[po->top--]; printf("\nThe popped element = %d",item); } }
Department of Electrical Engineering
//Function to print all the existing elements in the stack void traverse(NODE *pt) { int i; //if the top pointer points to NULL => stack is empty if(pt->top == -1) printf("\nThe stack is empty"); //otherwise all the elements in the stack are printed else { printf("\n\nThe stack contains:"); for(i=pt->top;i>=0;i--) printf("\nstack [%d] = %d",i,pt->stack[i]); } } int main() { int choice; NODE stack_structure; s=& stack_structure; s->top=-1; while(1) { printf("\n\n1.PUSH"); printf("\n2.POP"); printf("\n3.TRAVERSE"); printf("\n4.Quit\n"); printf("\nEnter Your Choice:"); scanf("%d",&choice); switch(choice) { case 1: push(s); break; M. Usman Aslam ([email protected]) Lecturer , RCET Gujranwala 2/3
IDE-11 Data Structures case 2: pop(s); break; case 3: traverse(s); break; case 4: return 0; default: printf("\nYou entered a wrong choice"); } } }
Department of Electrical Engineering
Lab Assignment Problems assigned by the lab teacher.
M. Usman Aslam ([email protected]) Lecturer , RCET Gujranwala
3/3