Learn Computer Science programming - C# and C++ Algorithms

 
Stack C++
A stack is a last in, first out (LIFO) data structure. A stack has two fundamental operations. Push and pop. The push operation adds to the top of the list, initializing the stack if it is empty. The pop operation removes an item from the top of the list, and returns this value to the caller.
Picture
Code
stack.zip
File Size: 1643 kb
File Type: zip
Download File

    //This Program to implement STack using Linear Single List

    #include<iostream>

    using namespace std;

    //Link List Strucure

     

    typedef struct Node

    {

    int d;

    Node* Next;

    }pNode;

     

    class Stack

    {

    private:

    Node* pHeader;

    public:

    Stack()

    {

    pHeader = NULL;

    };

    void Push(int d);

    int Pop();

    void Display();

    };

     

    void Stack::Push(int d)

    {

     

     

    Node* NewItem = new Node;

    NewItem->Next = pHeader;

    pHeader = NewItem;

    NewItem->d = d;

    }

    int Stack::Pop()

    {

    if (!pHeader) cout <<endl << "Stack is empty" << endl;

    else

    {

    int x = pHeader->d;

    Node* DeletedItem = pHeader;

    pHeader = pHeader->Next;

    delete DeletedItem;

    return x;

    }

    }

     

    void Stack::Display()

    {

    cout << endl;

    cout << endl << "Stack Content";

     

    while (pHeader->Next != NULL){

    cout << endl << pHeader->d;

    pHeader = pHeader->Next;

    }

    cout << endl << pHeader->d;

    }

     

     

    void main()

    {

    Stack S;

    cout << endl << "Pushing 1 into Stack";

    S.Push(1);

     

    cout << endl << "Pop...";

    cout << S.Pop();

     

    cout << endl << "Pushing 2,3,4 into Stack";

    S.Push(2);

    S.Push(3);

    S.Push(4);

     

    cout << endl << "Pop...";

    cout << S.Pop();

    cout << endl << "Pop...";

    cout << S.Pop();

     

    cout << endl << "Pushing 5,6,7,8 into Stack";

    S.Push(5);

    S.Push(6);

    S.Push(7);

    S.Push(8);

    cout << endl << "Pop...";

    cout << S.Pop();

    cout << endl << "Pop...";

    cout << S.Pop();

     

    S.Display ();

    int x;

    cin >> x;

     

    }

Output

  Pushing 1 into Stack
  Pop...1
  Pushing 2,3,4 into Stack
  Pop...4
  Pop...3
  Pushing 5,6,7,8 into Stack
  Pop...8
  Pop...7
  
Stack Content
  6
  5
  2