The program defines the storage structure of the chain stack (the chain storage structure of the stack) and implements the basic operation of the chain stack, such as: constructor, copy constructor and assignment operator overload function implementation, destructor, empty, insert, delete, get stack top element, traverse.
#include <iostream>using namespace Std;typedef int stackelement;struct node{Node *next;stackelement data;node (stackelement value, node *link = NULL):d ata (value), Next{}};class stack{public:stack (): Mytop (NULL) {} Stack (const stack& original) { mytop = NULL; if (!original.empty ()) { mytop = new Node (original. Top ());Copy the first node nodeptr lastptr = mytop;Set the pointer to traverse the entire stack of linked lists nodeptr origptr =original.mytop->next; While (origptr! = 0) { lastptr->next = new Node (origptr->data); lastptr = lastptr->next; origptr = origptr->next; } } }~stack () { nodeptr ptr = mytop, nextptr;PTR will be freed of nodes, Nextptr is PTR successor While (ptr!=0) { nextptr = ptr->next; delete ptr; ptr = nextptr; } }stack& operator= (const STACK&RHS) { if (THIS!=&RHS) { This->~stack ();Destroys the current linked list if (Rhs.empty ())Empty stack mytop = NULL; Else { mytop = new Node (RHS. Top ());Copy the first node nodeptr lastptr = mytop;Set the pointer to traverse the entire stack of linked lists nodeptr rhsptr = rhs.mytop->next; While (rhsptr! = 0) { Lastptr->next = new Node (rhsptr->data); lastptr = lastptr->next; rhsptr = rhsptr->next; } } }return *this; }stackelement Top () const { if (!empty ()) { return (mytop->data); } Else { cout << "The Stack is empty!" << Endl; } }bool Empty () const { return mytop==0; }void push (const stackelement& value) { mytop = new Node (value, mytop); }void Display () { nodeptr ptr; For (ptr = mytop; ptr = = 0; ptr = ptr->next) cout << ptr->data << ""; cout << Endl; }void pop () { if (!empty ()) { nodeptr ptr=mytop; mytop = mytop->next; delete ptr; } Else { cout << "Stack is empty" << Endl; } }Privatetypedef node* NODEPTR;nodeptr mytop;};void Main () {Stack S;cout<<s.empty () <<endl;For (Stackelement i = 1; i < 6; ++i){S.push (i);}cout << s.empty () << Endl;cout << s.top () << Endl;S.display ();S.pop ();S.display ();Stack S1 (s); S1. Display ();Stack S2;s2 = s;S2. Display ();System ("pause");}
Implementation of the Stack