Name : Areeba
Class: BS(IT)
Registration no: 132243277(ACB072)
ROLL NO : 6008
132243128
STACK DATA STRUCTURE USING LINKED MEMORY
#include <stdio.h>
#include <stdlib.h>
// Node structure
struct Node {
int data;
struct Node* next;
};
// Stack structure
struct Stack {
struct Node* top;
};
// Initialize stack
void initStack(struct Stack* stack) {
stack->top = NULL;
// Check if stack is empty
int isEmpty(struct Stack* stack) {
return stack->top == NULL;
}
// Push element
void push(struct Stack* stack, int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Memory allocation failed!\n");
return;
newNode->data = value;
newNode->next = stack->top;
stack->top = newNode;
printf("%d pushed\n", value);
// Pop element
int pop(struct Stack* stack) {
if (isEmpty(stack)) {
printf("Stack Underflow!\n");
return -1;
struct Node* temp = stack->top;
int value = temp->data;
stack->top = stack->top->next;
free(temp);
return value;
// Peek top element
int peek(struct Stack* stack) {
if (isEmpty(stack)) {
printf("Stack is empty\n");
return -1;
return stack->top->data;
// Display stack
void display(struct Stack* stack) {
if (isEmpty(stack)) {
printf("Stack is empty\n");
return;
struct Node* temp = stack->top;
printf("Stack (top to bottom): ");
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
printf("\n");
// Free entire stack
void freeStack(struct Stack* stack) {
while (!isEmpty(stack)) {
pop(stack);
}
int main() {
struct Stack stack;
initStack(&stack);
push(&stack, 10);
push(&stack, 20);
push(&stack, 30);
display(&stack);
printf("Top element: %d\n", peek(&stack));
printf("Popped: %d\n", pop(&stack));
display(&stack);
freeStack(&stack); // Clean up memory
return 0;