Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a Stack<T> is empty

Tags:

stack

c#

is-empty

Is there some other way, except Stack<T>.Count() == 0, to check if a Stack<T> is empty?

Coming from C++/Java background where "stack" classes generally have some sort of dedicated "is empty" method like Java - Stack.empty.

like image 932
BobsunShirov Avatar asked Sep 09 '14 15:09

BobsunShirov


People also ask

How do you know if a stack is empty?

Stack. empty() is used to check if a stack is empty or not. This method requires no parameters. It returns true if the stack is empty and false if the stack is not empty.

How do you check if a stack is empty or not in C++?

The stack. empty() function in C++ returns a true value (1) if the stack is empty. Otherwise, it returns false (0). In short, this function is used to check if the stack is empty.

How do I check if a stack is empty MIPS?

Capture the value of stack pointer before any of the dynamic pushing, and then as part of dynamic popping compare the current stack pointer with that previously captured stack pointer — when they are equal, there's nothing to pop.

How do I know if my stack is full?

push( x ) : insert element x at the top of stack. void push (int stack[ ] , int x , int n) { if ( top == n-1 ) { //if top position is the last of position of stack, means stack is full .


3 Answers

Instead of using .Count() == 0, just use .Count == 0. This is using the stack's property rather than the linq extension method.

like image 168
recursive Avatar answered Oct 19 '22 17:10

recursive


There are three common approaches, and which one you use will usually be a matter of taste.

if(!stack.Any()) ...
if(stack.Count() == 0) ...
if(stack.Count == 0) ...

Profiling the different approaches looks like this:

Benchmark

.Any() and .Count() take 10x-20x longer than .Count... and can still run tens of thousands of times per millisecond. So .Count > 0 is "much faster", but the others are still fast enough to not have to worry about under most circumstances. I'd personally stick with Any() since I feel it reads better, but I wouldn't give anyone flak for choosing Count.

like image 31
StriplingWarrior Avatar answered Oct 19 '22 16:10

StriplingWarrior


You can create your own extension method too

namespace System.Collection.Generic {
   public static class SystemEx {
        public static bool IsEmpty<T>(this Stack<T> stack) {
            return (stack.Count==0);
        }    
   }
like image 4
Blau Avatar answered Oct 19 '22 16:10

Blau