Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2025 Foundation Course
NEET 2025 Foundation Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
2.2k views
in Computer by (69.8k points)

Write a program to implement the stack using linked list.

1 Answer

+1 vote
by (69.2k points)
selected by
 
Best answer

A C program to implement the stack using linked list is given below:

/* Program to implement stack as linked list*/

/* structure containing data part and linkpart */ 

struct node 

{

int data ; 

struct node *link ;

printf("The stack currently contains\n");

display ( s ) ;

i = pop ( &s ) ;

printf ( "\nItem popped: %d", i ) ; 

i = pop ( &s ) ; 

printf ( "\nItem popped: %d", i ) ;

i = pop ( &s ) ; 

printf ( "\nItem popped: %d", i ) ; 

printf("Stack after deleting three items\n"); 

display (s); 

delstack ( &s ) ; 

getch( ) ; 

}

/* adds a new node to the stack as linked list */

void push ( struct node **top, int item ) 

{

struct node *temp ; 

temp = ( struct node * ) malloc ( sizeof ( struct node ) ) ; 

if ( temp == NULL ) 

printf ( "\nStack is full." ) ; 

temp -> data = item ; 

temp -> link = *top ; 

*top = temp ; 

}

/* pops an element from the stack */ 

int pop ( struct node **top )

{

struct node *temp ; 

int item ; 

if ( *top == NULL ) 

{

printf ( "\nStack is empty." ) ; 

return NULL ;

} temp = *top ; 

item = temp -> data ; 

*top = ( *top ) -> link ; 

free ( temp ) ; 

return item ;

}

/* displays the contents of the stack */

void display ( struct node *q )

{

printf ( "\n" ) ; 

/* traverse the entire stack */ 

while ( q != NULL ) 

{

printf ( "%d ", q -> data ) ; 

q = q -> link ;

/* deallocates memory */ 

void delstack ( struct node **top ) 

{

struct node *temp ; 

if ( *top == NULL ) 

return ; 

while ( *top != NULL ) 

{

temp = *top ; 

*top = ( *top ) -> link ; 

free ( temp ) ; 

}

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...