Skip to content

Instantly share code, notes, and snippets.

@ksksue
Created December 3, 2014 02:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ksksue/db3e27718bc846e16c8d to your computer and use it in GitHub Desktop.
Save ksksue/db3e27718bc846e16c8d to your computer and use it in GitHub Desktop.
@interface Queue : NSObject {
NSMutableArray *queue;
int maxSize;
}
- (id)initWithSize:(int)maxSize;
- (id)dequeue;
- (void)enqueue:(id)anObject ;
- (int)count;
@end
#import "Queue.h"
@implementation Queue
- (id)initWithSize:(int)aMaxSize{
self = [super init];
if (self != nil) {
queue = [[NSMutableArray alloc] init];
maxSize = aMaxSize;
}
return self;
}
- (id)dequeue {
id headObject;
@synchronized(queue){
if ([queue count] == 0) return nil;
headObject = [queue objectAtIndex:0];
if (headObject != nil) {
[queue removeObjectAtIndex:0];
}
}
return headObject;
}
- (void)enqueue:(id)anObject {
@synchronized(queue){
if (anObject == nil) {
return;
}
if ([queue count] >= maxSize) {
[queue removeObjectAtIndex:0];
}
[queue addObject:anObject];
}
}
- (int)count {
int c = 0;
@synchronized(queue) {
c = [queue count];
}
return c;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment