Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a stack item which is not on the top of the stack in C#

Tags:

stack

c#

Unfortunately an item can only be removed from the stack by "pop". The stack has no "remove" method or something similar, but I have a stack (yes I need a stack!) from which I need to remove some elements between.

Is there a trick to do this?

like image 539
Enyra Avatar asked Apr 14 '09 16:04

Enyra


People also ask

Can we delete from middle on stack?

Given a stack, delete the middle element of it without using any additional data structure. You can use basic stack operations like push(), pop() and empty(). The above example contains an odd number of elements, hence the middle element is clearly the N / 2th element, which is removed from the stack in the output.

How do I remove an item from a stack?

Stack. pop() method. This method requires no parameters and it removes the element at the top of the stack. It returns the element that was removed.

How do you delete top of stack?

Stack<T>. Pop Method is used to remove and returns the object at the top of the Stack<T>. This method comes under the System.


2 Answers

If you need to remove items that aren't on the top, then you need something other than a stack.

Try making your own implementation of a stack from a List. Then you get to implement your own push and pop functions (add & remove on the list), and your own special PopFromTheMiddle function.

For example

public class ItsAlmostAStack<T> {     private List<T> items = new List<T>();      public void Push(T item)     {         items.Add(item);     }     public T Pop()     {         if (items.Count > 0)         {             T temp = items[items.Count - 1];             items.RemoveAt(items.Count - 1);             return temp;         }         else             return default(T);     }     public void Remove(int itemAtPosition)     {         items.RemoveAt(itemAtPosition);     } } 
like image 138
Binary Worrier Avatar answered Sep 22 '22 07:09

Binary Worrier


Consider using different container. Maybe a LinkedList. Then you can use

AddFirst AddLast RemoveLast RemoveFirst

just like pop/push from stack and you can use

Remove

to remove any node from the middle of the list

like image 38
Michał Piaskowski Avatar answered Sep 22 '22 07:09

Michał Piaskowski