Implementing a Stack with NSMutableArray

Stacks are a fundamental data structure in computer science, used in various applications such as parsing expressions, backtracking algorithms, and managing function calls. In this tutorial, we will explore how to implement a stack using NSMutableArray in Objective-C. This guide is designed for beginners, so don’t worry if you’re new to programming or data structures!

Prerequisites

Before we dive into the implementation, make sure you have the following:

  • A basic understanding of the Objective-C programming language.
  • Xcode installed on your Mac to write and run Objective-C code.
  • Familiarity with arrays and their operations.

What is a Stack?

A stack is a collection of elements that follows the Last In, First Out (LIFO) principle. This means that the last element added to the stack is the first one to be removed. You can think of it like a stack of plates: you add new plates to the top and also remove them from the top.

Implementing a Stack with NSMutableArray

Now, let’s implement a stack using NSMutableArray. We will create a simple class called Stack that will encapsulate the stack operations.

Step 1: Create the Stack Class

#import <Foundation/Foundation.h>

@interface Stack : NSObject
@property (nonatomic, strong) NSMutableArray *elements;
- (void)push:(id)element;
- (id)pop;
- (id)peek;
- (BOOL)isEmpty;
@end

In this code snippet, we define a Stack class with a property called elements, which is an NSMutableArray that will hold our stack items. We also declare four methods:

  • push: Adds an element to the top of the stack.
  • pop: Removes and returns the top element from the stack.
  • peek: Returns the top element without removing it.
  • isEmpty: Checks if the stack is empty.

Step 2: Implement the Methods

Next, we will implement the methods we declared in the Stack class.

@implementation Stack

- (instancetype)init {
    self = [super init];
    if (self) {
        _elements = [NSMutableArray array];
    }
    return self;
}

- (void)push:(id)element {
    [self.elements addObject:element];
}

- (id)pop {
    if ([self isEmpty]) {
        return nil;
    }
    id topElement = [self.elements lastObject];
    [self.elements removeLastObject];
    return topElement;
}

- (id)peek {
    return [self.elements lastObject];
}

- (BOOL)isEmpty {
    return [self.elements count] == 0;
}

@end

Here’s a breakdown of each method:

  • init: Initializes the stack and creates an empty NSMutableArray.
  • push: Adds the provided element to the end of the array, which represents the top of the stack.
  • pop: Checks if the stack is empty. If not, it retrieves the last element (top of the stack) and removes it from the array.
  • peek: Simply returns the last element without modifying the stack.
  • isEmpty: Returns YES if the stack has no elements, otherwise NO.

Using the Stack

Now that we have our stack implementation, let’s see how to use it in a simple example.

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Stack *stack = [[Stack alloc] init];
        [stack push:@1];
        [stack push:@2];
        [stack push:@3];

        NSLog(@"Top element: %@", [stack peek]); // Output: 3
        NSLog(@"Popped element: %@", [stack pop]); // Output: 3
        NSLog(@"Is stack empty? %@", [stack isEmpty] ? @"YES" : @"NO"); // Output: NO
    }
    return 0;
}

In this example, we create a new stack, push three integers onto it, and then use the peek and pop methods to interact with the stack. The output will show the top element and the result of popping the top element.

Conclusion

Congratulations! You have successfully implemented a stack using NSMutableArray in Objective-C. Stacks are a powerful data structure that can be used in various applications. By understanding how to implement them, you are building a solid foundation for more complex data structures and algorithms.

For further reading and resources, check out the following links:

  • Continue reading on Medium »”>Understanding Data Structures
  • More on Objective-C Programming

Source: Original Article