mirror of
https://github.com/Manoj-HV30/ds-lab-codes.git
synced 2026-05-16 19:35:22 +00:00
rest of the codes
This commit is contained in:
+101
@@ -0,0 +1,101 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
// Node structure
|
||||
typedef struct node {
|
||||
int data;
|
||||
struct node *next;
|
||||
} NODE;
|
||||
|
||||
NODE *top = NULL;
|
||||
|
||||
// Push operation
|
||||
void push(int value) {
|
||||
NODE *newNode = (NODE*)malloc(sizeof(NODE));
|
||||
|
||||
if (!newNode) {
|
||||
printf("Memory allocation failed!\n");
|
||||
return;
|
||||
}
|
||||
|
||||
newNode->data = value;
|
||||
newNode->next = top;
|
||||
top = newNode;
|
||||
|
||||
printf("Pushed %d onto stack\n", value);
|
||||
}
|
||||
|
||||
// Pop operation
|
||||
int pop() {
|
||||
NODE *temp;
|
||||
int value;
|
||||
|
||||
if (top == NULL) {
|
||||
printf("Stack Underflow! Stack is empty.\n");
|
||||
return -1;
|
||||
}
|
||||
|
||||
temp = top;
|
||||
value = temp->data;
|
||||
top = top->next;
|
||||
free(temp);
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
// Display stack contents
|
||||
void display() {
|
||||
NODE *temp = top;
|
||||
|
||||
if (top == NULL) {
|
||||
printf("Stack is empty.\n");
|
||||
return;
|
||||
}
|
||||
|
||||
printf("Stack contents:\n");
|
||||
while (temp != NULL) {
|
||||
printf("%d -> ", temp->data);
|
||||
temp = temp->next;
|
||||
}
|
||||
printf("NULL\n");
|
||||
}
|
||||
|
||||
// Main menu
|
||||
int main() {
|
||||
int choice, value;
|
||||
|
||||
while (1) {
|
||||
printf("\n--- STACK MENU ---\n");
|
||||
printf("1. Push\n");
|
||||
printf("2. Pop\n");
|
||||
printf("3. Display\n");
|
||||
printf("4. Exit\n");
|
||||
printf("Enter choice: ");
|
||||
scanf("%d", &choice);
|
||||
|
||||
switch (choice) {
|
||||
case 1:
|
||||
printf("Enter value to push: ");
|
||||
scanf("%d", &value);
|
||||
push(value);
|
||||
break;
|
||||
|
||||
case 2:
|
||||
value = pop();
|
||||
if (value != -1)
|
||||
printf("Popped value: %d\n", value);
|
||||
break;
|
||||
|
||||
case 3:
|
||||
display();
|
||||
break;
|
||||
|
||||
case 4:
|
||||
printf("Exiting...\n");
|
||||
exit(0);
|
||||
|
||||
default:
|
||||
printf("Invalid choice. Try again.\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user