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
