0% found this document useful (0 votes)
6 views4 pages

Stack SLL

Uploaded by

jeonirene9705
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)
6 views4 pages

Stack SLL

Uploaded by

jeonirene9705
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
You are on page 1/ 4

#include <stdio.

h>

#include <stdlib.h>

// Define the structure for a node

Struct Node {

Int data;

Struct Node* next;

};

Int main() {

Struct Node* top = NULL; // Pointer to the top of the stack

Int choice, value;

While (1) {

// Display menu options

Printf(“\nStack Operations Menu:\n”);

Printf(“1. Push\n”);

Printf(“2. Pop\n”);

Printf(“3. Peek\n”);

Printf(“4. Display\n”);

Printf(“5. Exit\n”);

Printf(“Enter your choice: “);

Scanf(“%d”, &choice);

Switch (choice) {

Case 1: // Push operation

Printf(“Enter the value to push: “);


Scanf(“%d”, &value);

// Create a new node

Struct Node* newNode = (struct Node*)malloc(sizeof(struct


Node));

newNode->data = value;

newNode->next = top; // Point new node to the current top

top = newNode; // Update top to the new node

printf(“Pushed %d onto the stack.\n”, value);

break;

case 2: // Pop operation

if (top == NULL) {

printf(“Stack is empty! Cannot pop.\n”);

} else {

Struct Node* temp = top;

Top = top->next; // Move top to the next node

Printf(“Popped %d from the stack.\n”, temp->data);

Free(temp); // Free memory of the popped node

Break;

Case 3: // Peek operation

If (top == NULL) {

Printf(“Stack is empty! Cannot peek.\n”);

} else {
Printf(“Top element is %d.\n”, top->data);

Break;

Case 4: // Display stack

If (top == NULL) {

Printf(“Stack is empty! Nothing to display.\n”);

} else {

Struct Node* current = top;

Printf(“Stack elements: “);

While (current != NULL) {

Printf(“%d “, current->data);

Current = current->next;

Printf(“\n”);

Break;

Case 5: // Exit

Printf(“Exiting program.\n”);

Exit(0);

Default:

Printf(“Invalid choice! Please try again.\n”);

}
Return 0;

You might also like