C++ exercises and solutions: Add an item to the Stack


Stack

Add an item to the Stack


Step 2: Adding an item to the Stack

In the Stack data structure, an item is allowed to be added only to the beginning of the list. To add a new item to Stack, you need to consider two things--empty stack and none-empty stack. If the Stack is empty, you simply let the pfirst and plast point to the new item. The next link of the item that doesn't point to other item should be NULL. If the Stack is not empty, you can let the next link of the new item point to the pfirst and then update the pfirst to point to the new item.

Adding an item to the beginning of the Stack  

The C++ code to add an item to Stack is shown below:

//Add an item to the Stack
void Push (int val)
{

int t;
ListElem *item;//new element to be Pushed
item=(ListElem *)malloc(sizeof(ListElem)); //allocate space
if(!item) {cout<<"Memory problem..."<<endl; exit(100);}

item->data=val;

//Push a new item to the empty stack

if(pfirst==NULL && plast==NULL){
//The first and last item point to the new item when they are null--empty stack.
item->next=NULL;
pfirst=item;
plast=item;

cout<<"Pushed:"<<item->data<<endl;

}

//Push a new item at the beginning of the stack
else
{

item->next=pfirst;
pfirst=item;
cout<<"Pushed"<<item->data<<endl;
}



}




Comments




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.