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

lab2.q2

Uploaded by

Milica Markovic
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

lab2.q2

Uploaded by

Milica Markovic
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <stdio.

h>
#include <stdlib.h>

typedef struct Node {


int data;
struct Node* next;
} Node;

typedef struct Stack {


Node* top;
int size;
} Stack;

// Function to initialize a stack


Stack* initStack() {
Stack* stack = (Stack*)malloc(sizeof(Stack));
if (stack == NULL) {
printf("Memory allocation error\n");
exit(EXIT_FAILURE);
}
stack->top = NULL;
stack->size = 0;
return stack;
}

// Function to push an element onto the stack


void push(Stack* stack, int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (newNode == NULL) {
printf("Memory allocation error\n");
exit(EXIT_FAILURE);
}
newNode->data = data;
newNode->next = stack->top;
stack->top = newNode;
stack->size++;
}

// Function to pop an element from the stack


void pop(Stack* stack) {
if (stack->size == 0) {
printf("Stack is empty. Cannot pop.\n");
return;
}
Node* temp = stack->top;
stack->top = stack->top->next;
free(temp);
stack->size--;
}

// Function to get the top element of the stack


int top(Stack* stack) {
if (stack->size == 0) {
printf("Stack is empty.\n");
exit(EXIT_FAILURE);
}
return stack->top->data;
}
// Function to get the size of the stack
int stackSize(Stack* stack) {
return stack->size;
}

int main() {
Stack* stack = initStack();

// Push elements onto the stack


push(stack, 10);
push(stack, 20);
push(stack, 30);

printf("Stack size: %d\n", stackSize(stack));


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

// Pop elements from the stack


pop(stack);
printf("Popped an element.\n");

printf("Stack size after pop: %d\n", stackSize(stack));


printf("Top element after pop: %d\n", top(stack));

// Free allocated memory for the stack


Node* current = stack->top;
Node* next;
while (current != NULL) {
next = current->next;
free(current);
current = next;
}
free(stack);

return 0;
}

You might also like