Last active
January 3, 2016 23:18
-
-
Save thuai/8533866 to your computer and use it in GitHub Desktop.
Add queue and stack implemention to NSMutableArray class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
@interface NSMutableArray (QueueAndStack) | |
-(id)queuePop; | |
-(void)queuePush:(id)obj; | |
-(id)stackPop; | |
-(void)stackPush:(id)obj; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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