#include<iostream>
#include<string>
using namespace std;
struct Node
{
string data;
Node * next;
};
void push(Node **top, string argData);
string pop(Node **top);
string peek(Node *top);
void erase(Node **top);
void display(Node *top);
int main()
{
Node * top=NULL;
//Testing push
push(&top, "임영동");
push(&top, "20021035");
push(&top, "컴퓨터공학과");
display(top);
//Testing pop
cout<<"Pop the top of the node: "<<pop(&top)<<endl;
display(top);
//Testing peek;
cout<<"Peek the top of the node: "<<peek(top)<<endl;
//Testing erase;
erase(&top);
display(top);
return 0;
}
void push(Node **top, string argData)
{
Node * temp;
temp=new Node;
temp->data=argData;
temp->next=*top;//Indicate the highest node of stack
*top=temp;//Top links to the new element
}
string pop(Node **top)
{
Node * temp;
string tempData;
temp=*top;
if(temp==NULL)
{//If your stack is empty
cout<<"Stack is empty now."<<endl;
exit(1);
}
else
{//If your stack has one element at least
tempData=temp->data;
*top=temp->next;
delete temp;
return tempData;
}
}
string peek(Node *top)
{
string tempData;
if(top==NULL)
{//If your stack is empty
cout<<"Stack is empty now."<<endl;
exit(1);
}
else
{//If your stack has one element at least
tempData=top->data;
return tempData;
}
}
void erase(Node **top)
{
Node *temp;
if(*top==NULL)
{//If your stack is empty
cout<<"Stack is empty now."<<endl;
exit(1);
}
else
{
temp=*top;
*top=(*top)->next;
delete temp;
}
}
void display(Node *top)
{
cout<<"----Stack----"<<endl;
Node * tempNode; //Temporary node to tour linked list
tempNode=top;
do{
if(tempNode==NULL)
{
cout<<"Sorry... There is no node to display.\n";
break;
}
else
{
cout<<tempNode->data<<"\n";
if(tempNode->next==NULL)//Exit from do-while loop if value of next node is null
break;
else //Go to the next node if there is next node
tempNode=tempNode->next;
}
}while(1);
}