Stacks and Queues

I usually find these two simple data structures (Stack and Queues) more than useful… So using a NSMutableArray we can code their behaviour quite easily.

So here you go:

The Queue

@interface NSMutableArray (CPQueue)
- (void)add:(id)object;
- (id)remove;
- (id)first;
- (id)last;
@end
 
@implementation NSMutableArray (CPQueue)
- (void)add:(id)object{
    if(object) [self addObject:object];
}
 
- (id)remove{
    id theResult = nil;
    if([self count]){
        theResult = [[[self objectAtIndex:0] retain] autorelease];
        [self removeObjectAtIndex:0];
    }
    return theResult;
}
 
- (id)first{
    return [self objectAtIndex:0];
}
 
- (id)last{
    return [self lastObject];
}
@end

The Stack

@interface NSMutableArray (CPStack)
- (void)push:(id)object;
- (id)pop;
- (id)top;
@end
 
@implementation NSMutableArray (CPStack)
- (void)push:(id)object{
    if(object) [self addObject:object];
}
 
- (id)pop
{
    id theResult = nil;
    if([self count])
    {
        theResult = [[[self lastObject] retain] autorelease];
        [self removeLastObject];
    }
    return theResult;
}
 
- (id)top
{
    return [self lastObject];
}
@end

Infix to Postfix in Cocoa

Hi, recently I have been working on this infix to postfix notation converter in C++ for my data structures module at the university. I also discovered that Objective-C does not have templates like C++ to create an abstract data type.

Anyway, the infix to postfix requires the use of a Stack and as you can see here there is a way to implement this behaviour using a NSMutableArray.

Grab the source code - InfixToPostfix – The code is based on this java implementation. Click here to read more »