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.
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.
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.
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.
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 .
Instead of using .Count() == 0
, just use .Count == 0
. This is using the stack's property rather than the linq extension method.
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:
.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
.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With