Simple Stack Program using pointers in C++ Programming


Definition

A stack is a basic computer science data structure and can be defined in an abstract, implementation-free manner, or it can be generally defined as a linear list of items in which all additions and deletion are restricted to one end that is Top.

Simple Stack Program using pointers in C++ Programming

/* Simple Stack Program Example Using Pointers in C++*/
/* Data Structure Programs,Stack Programs,C++ Examples */

#include<iostream>
#include<conio.h>
#include<stdlib.h>

#define MAX_SIZE 3

using namespace std;

void push(int i);
void pop(void);

int choice, i;
int *tos, *p1, arr_stack[MAX_SIZE];
int exit_p = 1;

int main() {

    int value;

    tos = arr_stack; /* tos points to the top of stack */
    p1 = arr_stack; /* initialize p1 */
    cout << "\nSimple Stack Example - Pointers";

    do {
        cout << "\nStack Pointer : Main Menu";

        cout << "\n1.Push \t2.Pop \tOthers to exit : Your Choice : ";
        cin>>choice;
        switch (choice) {
            case 1:
                cout << "Enter value: ";
                cin>>value;
                push(value);
                break;
            case 2:
                pop();
                break;
            default:
                exit_p = 0;
                break;
        }
    } while (exit_p);

    return 0;
}

void push(int i) {
    if (p1 == (tos + MAX_SIZE)) {
        cout << "\nStatus : Stack Overflow.\n";
    } else {
        *p1 = i;
        cout << "\nPush Value : %d " << *(p1);
        p1++;
    }
}

void pop(void) {
    if (p1 == tos) {
        cout << "\nStatus : Stack Underflow.";
        //return 0;
    } else {
        p1--;
        cout << "\nPop Value : %d " << *(p1);
    }
}


Sample Output

Simple Stack Example - Array and Pointers
Stack Pointer : Main Menu
1.Push  2.Pop   Others to exit : Your Choice : 1
Enter value: 100

Push Value : 100
Stack Pointer : Main Menu
1.Push  2.Pop   Others to exit : Your Choice : 1
Enter value: 200

Push Value : 200
Stack Pointer : Main Menu
1.Push  2.Pop   Others to exit : Your Choice : 1
Enter value: 300

Push Value : 300
Stack Pointer : Main Menu
1.Push  2.Pop   Others to exit : Your Choice : 1
Enter value: 400

Status : Stack Overflow.

Stack Pointer : Main Menu
1.Push  2.Pop   Others to exit : Your Choice : 1
Enter value: 500

Status : Stack Overflow.

Stack Pointer : Main Menu
1.Push  2.Pop   Others to exit : Your Choice : 1
Enter value: 2

Status : Stack Overflow.

Stack Pointer : Main Menu
1.Push  2.Pop   Others to exit : Your Choice : 2

Pop Value : 300
Stack Pointer : Main Menu
1.Push  2.Pop   Others to exit : Your Choice : 2

Pop Value : 200
Stack Pointer : Main Menu
1.Push  2.Pop   Others to exit : Your Choice : 2

Pop Value : 100
Stack Pointer : Main Menu
1.Push  2.Pop   Others to exit : Your Choice : 2

Status : Stack Underflow.

Stack Pointer : Main Menu
1.Push  2.Pop   Others to exit : Your Choice : 3