Skip to content

Instantly share code, notes, and snippets.

@thuai
Last active January 3, 2016 23:18
Show Gist options
  • Save thuai/8533866 to your computer and use it in GitHub Desktop.
Save thuai/8533866 to your computer and use it in GitHub Desktop.
Add queue and stack implemention to NSMutableArray class
#import <Foundation/Foundation.h>
@interface NSMutableArray (QueueAndStack)
-(id)queuePop;
-(void)queuePush:(id)obj;
-(id)stackPop;
-(void)stackPush:(id)obj;
@end
#import "NSMutableArray+QueueAndStack.h"
@implementation NSMutableArray (QueueAndStack)
// Queues are first-in-first-out, so we remove objects from the head
-(id)queuePop {
if ([self count] == 0) {
return nil;
}
id queueObject = [self objectAtIndex:0];
[self removeObjectAtIndex:0];
return queueObject;
}
// Add to the tail of the queue
-(void)queuePush:(id)anObject {
[self addObject:anObject];
}
//Stacks are last-in-first-out.
-(id)stackPop {
id lastObject = [self lastObject];
if (lastObject)
[self removeLastObject];
return lastObject;
}
-(void)stackPush:(id)obj {
[self addObject: obj];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment