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

8

Uploaded by

nn4489
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views2 pages

8

Uploaded by

nn4489
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <stdio.

h>
#include <stdlib.h>

struct StackNode {
int data;
struct StackNode* next;
};
struct Stack {
struct StackNode* top;
};

struct Stack* createStack() {


struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));
stack->top = NULL;
return stack;
}

int isEmpty(struct Stack* stack) {


return stack->top == NULL;
}

void push(struct Stack* stack, int data) {


struct StackNode* newNode = (struct StackNode*)malloc(sizeof(struct
StackNode));
newNode->data = data;
newNode->next = stack->top;
stack->top = newNode;
}

int pop(struct Stack* stack) {


if (isEmpty(stack)) {
printf("Stack Underflow\n");
return -1; // Return -1 to indicate stack is empty
}
struct StackNode* temp = stack->top;
int popped = temp->data;
stack->top = stack->top->next;
free(temp);
return popped;
}

int peek(struct Stack* stack) {


if (isEmpty(stack)) {
printf("Stack is empty\n");
return -1; // Return -1 to indicate stack is empty
}
return stack->top->data;
}

void printStack(struct Stack* stack) {


struct StackNode* temp = stack->top;
printf("Stack: ");
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
void freeStack(struct Stack* stack) {
while (!isEmpty(stack)) {
pop(stack);
}
free(stack);
}

int main() {
struct Stack* stack = createStack();
push(stack, 10);
push(stack, 20);
push(stack, 30);

printf("Original Stack: ");


printStack(stack);

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


printf("Popped element is %d\n", pop(stack));
printf("Stack after pop: ");
printStack(stack);

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

freeStack(stack);
return 0;
}

You might also like