Monday, 7 March 2022

3 - Stack Using Singly Linked List

3 - Stack Using Singly Linked List

GFG

#include <bits/stdc++.h> using namespace std; struct Node { int data; Node* link; }; Node* top; void push(int data) { Node* temp = new Node(); if (!temp) { cout << "\nStack Overflow"; exit(1); } temp->data = data; temp->link = top; top = temp; } int isEmpty() { return top == NULL; } int peek() { if (!isEmpty()) return top->data; else exit(1); } void pop() { Node* temp; if (top == NULL) { cout << "\nStack Underflow" << endl; exit(1); } else { temp = top; top = top->link; free(temp); } } void display() { Node* temp; if (top == NULL) { cout << "\nStack Underflow"; exit(1); } else { temp = top; while (temp != NULL) { cout << temp->data << "-> "; temp = temp->link; } } } int main() { push(11); push(22); push(33); push(44); display(); cout << "\nTop element is " << peek() << endl; pop(); pop(); display(); cout << "\nTop element is " << peek() << endl; return 0; }

Own Code

#include <bits/stdc++.h>
using namespace std;

struct node {
    struct node* prev;
    int val;
    struct node* next;
} *head = 0, *ptr1, *ptr2, *temp, *new1;

int main() {
    int ch, x, c = 0;
    char res;
    do {
        printf("\n1.Push\n2.Pop\n3.Display\nChoose any 1 : \t");
        scanf("%d", &ch);
        switch(ch) {
            case 1:
                do {
                    printf("\nEnter value : \t");
                    scanf("%d", &x);
                    new1 = (struct node*)malloc(sizeof(struct node));
                    new1->prev = 0;
                    new1->val = x;
                    new1->next = 0;
                    if(head == 0) {
                        head = new1;
                        c++;
                    } else {
                        temp = head;
                        while(temp->next != 0) {
                            temp = temp->next;
                        }
                        temp->next = new1;
                        new1->prev = temp;
                        c++;
                    }
                    printf("\nDo you want to add more values ?: \t");
                    scanf(" %c", &res);
                } while(res == 'y');
            break;

            case 2:
            break;

            case 3:
                temp = head;
                while(temp->next != 0) {
                    temp = temp->next;
                }
                while(temp != head) {
                    printf("%d\n", temp->val);
                    temp = temp->prev;
                }
                printf("%d\n", head->val);
            break;
        }
        printf("\nDo you want to continue? : \t");
        scanf(" %c", &res);
    } while(res == 'y');
}

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home