C# OOP: Stack

Remove item from Stack


Step 4: Remove item of the Stack

The Stack allows you to remove its first item only. The removing the item process can be done at the beginning of list. When the Stack contains only one element, you just assign the null values to the pfirst and plast.

If the Stack contains more than one item, You will need a temporary link(temp) to point to the first element and update the pfirst to point to its next item. Then assign null value to the temporary link.

The C#(Csharp) code to remove an item from the Stack is shown below:

//delete an item from the Stack

public ListNode<T> pop()
{
  ListNode<T> temp,del;
  if (countitem() > 0)
  { //make sure the list is not empty.

//delete the first item
   if(countitem()==1){ //The list contains only one item
    del=pfirst;
    pfirst=null;
    plast=null;

}
  else{ //The list contains more than one item
   temp=pfirst;
   del=temp;
   pfirst=pfirst.next;
   temp=null;
  } 

 return del;


}



else return null;

}




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.