0% found this document useful (0 votes)
9 views

Ds New Input 5

Hi

Uploaded by

Kaushal Sahni
Copyright
© © All Rights Reserved
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)
9 views

Ds New Input 5

Hi

Uploaded by

Kaushal Sahni
Copyright
© © All Rights Reserved
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/ 3

#include <stdio.

h>

#include <stdlib.h>

struct Node {

int data;

struct Node* next;

};
void push(struct Node** top_ref, int new_data) {
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
if (new_node == NULL) {

printf("Stack Overflow\n");

return;

}
new_node->data = new_data;

new_node->next = (*top_ref);

(*top_ref) = new_node;

printf("%d pushed onto stack\n", new_data);

int pop(struct Node** top_ref) {

if (*top_ref == NULL) {

printf("Stack Underflow\n");

return -1;

}
struct Node* temp = *top_ref;

int popped_data = temp->data;

*top_ref = temp->next;

free(temp);

return popped_data;

int peek(struct Node* top) {

if (top == NULL) {

printf("Stack is empty\n");

return -1;

}
return top->data;

void traverse(struct Node* top) {

if (top == NULL) {

printf("Stack is empty\n");

return;

struct Node* temp = top;

printf("Stack elements: ");

while (temp != NULL) {

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

temp = temp->next;
}

printf("\n");

int main() {

struct Node* stack = NULL;

push(&stack, 10);

push(&stack, 20);

push(&stack, 30);

traverse(stack);

printf("Top element is %d\n", peek(stack));

printf("%d popped from stack\n", pop(&stack));

printf("%d popped from stack\n", pop(&stack));

traverse(stack);

printf("Top element is %d\n", peek(stack));

return 0;

You might also like