0% found this document useful (0 votes)
78 views2 pages

Stack Implementation in C

This C program implements a stack using a linked list. It allows the user to push elements onto the stack, pop elements off the stack, and peek at the top element of the stack. The main function contains a do-while loop that prompts the user for an action and calls the appropriate function to perform the action. The push function allocates memory for a new node and adds it to the top of the stack. The pop function removes and returns the top element, freeing the memory. Peek simply returns the top element without removing it.

Uploaded by

happyskd1993
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
78 views2 pages

Stack Implementation in C

This C program implements a stack using a linked list. It allows the user to push elements onto the stack, pop elements off the stack, and peek at the top element of the stack. The main function contains a do-while loop that prompts the user for an action and calls the appropriate function to perform the action. The push function allocates memory for a new node and adds it to the top of the stack. The pop function removes and returns the top element, freeing the memory. Peek simply returns the top element without removing it.

Uploaded by

happyskd1993
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Stack using linked list

#include<stdio.h> #include<conio.h> struct stack { int info; struct stack *next; }; struct stack *top; void push(int element); int pop(); int peek(); void main() { int info,a,x,y; char ch; clrscr(); top=NULL; do { printf("Enter your choice\n1:Push\n2:Pop\n"); printf("3:Access the top element\n"); scanf("%d",&a); if(a==1) { printf("Enter the element\n"); scanf("%d",&info); push(info); } else if(a==2) { x=pop(); if(x==0) printf("Stack is empty\n"); else printf("Element deleted: %d\n",x); } else if(a==3) { y=peek(); printf("Top element: %d\n",y); } printf("Do you want to continue? y/n\n"); scanf(" %c",&ch); clrscr(); } while(ch=='y');

} void push(int element) { struct stack *newptr; newptr=(struct stack *)malloc(sizeof(struct stack)); if(newptr==NULL)

} int pop() { int value; struct stack *ptr; if(top==NULL) return 0; else { value=top->info; ptr=top; top=top->next; free(ptr); return value; } } int peek() { return (top->info); }

} else { newptr->info=element; newptr->next=top; top=newptr; }

printf("No memory available\n"); return;

Output

You might also like