0% found this document useful (0 votes)
3 views3 pages

Stack Using Pointer

The document contains a C program that implements a stack using a linked list. It includes functions for pushing, popping, peeking, and displaying the stack elements. The main function demonstrates these operations by pushing three integers onto the stack, displaying the stack, and then popping an element while showing the top element.

Uploaded by

tejaff20
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)
3 views3 pages

Stack Using Pointer

The document contains a C program that implements a stack using a linked list. It includes functions for pushing, popping, peeking, and displaying the stack elements. The main function demonstrates these operations by pushing three integers onto the stack, displaying the stack, and then popping an element while showing the top element.

Uploaded by

tejaff20
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

#include <stdio.

h>
#include <stdlib.h>

struct Node {
int data;
struct Node *link;
};

struct Node *top = NULL;

// ---- PUSH ----


void push(int x) {
struct Node *temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = x;
temp->link = top;
top = temp;
printf("Pushed %d\n", x);
}

// ---- POP ----


int pop() {
if (top == NULL) {
printf("Stack Underflow\n");
return -1;
}
struct Node *temp = top;
int val = temp->data;
top = top->link;
free(temp);
return val;
}

// ---- PEEK ----


int peek() {
if (top == NULL) {
printf("Stack Empty\n");
return -1;
}
return top->data;
}

// ---- DISPLAY ----


void display() {
if (top == NULL) {
printf("Stack Empty\n");
return;
}
struct Node *temp = top;
printf("Stack: ");
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->link;
}
printf("\n");
}

int main() {
push(10);
push(20);
push(30);

display();

printf("Popped: %d\n", pop());


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

display();

return 0;
}

You might also like