WHAT'S NEW?
Loading...

Stack implemented in linked list


/*Stack implemented in linked list*/
#include<stdio.h>

struct llist {
    int info;
    struct llist *next;
};
struct llist *tos;

void push() {
    struct llist *nnode;
    nnode = (struct llist *) malloc(sizeof(struct llist));
    printf("\nEnter the data: ");
    scanf("%d", &nnode->info);
    nnode->next = tos;
    tos = nnode;
}

void pop() {
    struct llist *temp;
    if (tos == NULL) {
        printf("\nEmpty stack!");
        return;
    }
    temp = tos;
    tos = temp->next;
    printf("\nThe deleted item is: %d", temp->info);
    free(temp);
}

void display() {
    struct llist *temp;
    if (tos == NULL) {
        printf("\nEmpty stack!");
        return;
    }
    temp = tos;
    printf("\nThe stack items are:\n");
    while (temp->next != NULL) {
        printf("%5d", temp->info);
        temp = temp->next;
    }
    printf("%5d", temp->info);
}

void main() {
    int ch;
    tos = NULL;
    while (1) {
        printf("\nMENU");
        printf("\n1.Push\n2.Pop\n3.Display all elements");
        printf("\n4.Exit\n\nEnter the choice: ");
        scanf("%d", &ch);
        switch (ch) {
        case 1:
            push();
            break;
        case 2:
            pop();
            break;
        case 3:
            display();
            break;
        case 4:
            exit(1);
        default:
            printf("\nInvalid Choice!\n");
        }
    }
}

0 comments:

Post a Comment