In Java there is a nice library class java.util.Stack which implements push and pop methods. Is there anything similar in Objective C?
I found only MutableArray. Seems weird I'd have to implement such a basic thing as a stack, there must be something like "NSStack", "NSQueue" and other similar stuff.
Stack is a container of objects that are inserted and removed according to the last-in first-out (LIFO) principle. Queue is a container of objects (a linear collection) that are inserted and removed according to the first-in first-out (FIFO) principle.
Stacks are based on the LIFO principle, i.e., the element inserted at the last, is the first element to come out of the list. Queues are based on the FIFO principle, i.e., the element inserted at the first, is the first element to come out of the list.
A stack is a linear data structure, collection of items of the same type. Stack follows the Last In First Out (LIFO) fashion wherein the last element entered is the first one to be popped out. In stacks, the insertion and deletion of elements happen only at one endpoint of it.
stack is a linked list that allows insertion / removal only from its tail, and. queue is a linked list that allows insertion only at its tail and removal only from its head.
Nobody should forget Objective-C offers a pretty nice variant: Objective-C++. And the C++ standard library provides the data structures you need, well tested, debugged, stable, and as fast as possible. Best, they'll work with ARC perfectly. Bestest, you can even choose between __weak
or __strong
pointers if you feels it.
Have a look at <queue>
and <stack>
.
That said, NSMutableArray
works perfectly well for stacks: -addObject:
, -lastObject
and -removeLastObject
will do the job nicely with good performance.
C++ can be verbose. Horribly verbose. But it also have some elegance here and there, and some very powerful constructs. Some parts of the standard library truly shine, and the data structures are among the pearls once the alien syntax is mastered. It can be hidden with a few typedefs anyway.
You (like myself) may worry about the dequeue performance of using NSMutableArray, because in dequeue you have to remove the first object in the NSMutableArray, and the removal will cause shifting of all the objects in the array. That is not necessary however based on the test I did here: for an NSMutableArray containing 100000 objects, remove all objects by continuously removing the first object is 100ms slower than by continuously removing the last object. I also compared using one NSMutableArray with using two NSMutableArrays. Although it's possible to avoid removing first object by using two NSMutableArrays which are used as two stacks, the double stack solution is actually slower.
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