Stack using Linked List


Stack using linked list
/*******************************************************************************/
#include<stdio.h>
#include<conio.h>
#include <stdlib.h>
struct Node
{
 int data;
 struct Node *next;
};
struct Node *top=NULL;

void push(int value) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = value;
    newNode->next = top;
    top = newNode;
}

int pop() {
    if (top == NULL) {
        printf("Stack is empty.\n");
        return -1;  // or any value to indicate an error
    }

    int poppedValue = top->data;
    struct Node* temp = top;
    top = top->next;
    free(temp);

    return poppedValue;
}

void displayStack() {
    if (top == NULL) {
        printf("Stack is empty.\n");
    } else {
        struct Node* temp = top;
        printf("Stack content:\n");
        while (temp != NULL) {
            printf("%d\n", temp->data);
            temp = temp->next;
        }
    }
}
void main()
{
 int ch;
 
 do
 {
  printf("\nMenu\n----\n1. Push\n2. Pop\n3.display\n4. Exit");
  printf("\nEnter the choice:");
  scanf("%d",&ch);
  switch(ch)
  {
   case 1:
        printf("Enter the data to push:");
        int data;
        scanf("%d",&data);
        push(data);
        displayStack();
         break;
   case 2:
        int rv;
        rv=pop();
        if(rv!=-1) printf("Popped Value is:%d\n",rv);
        displayStack();
        break;
   case 3:
    displayStack();
    break;
   case 4:
    exit(0);
   default:
    printf("There is no such operation:");
  }
 }
 while(1);
}

Comments

Popular posts from this blog

Data Structure Lab CSL 201 Manual KTU - Dr Binu V P-9847390760

Singly Linked List Implementation

Binary search Tree Implementation and Traversal