#import "NSMutableArray+QueueStack.h"
@implementation NSMutableArray (QueueStack)
// Queues are first-in-first-out, so we remove objects from the head
-(id)queuePop {
@synchronized(self)
{
if ([self count] == 0) {
return nil;
}
id queueObject = [[[self objectAtIndex:0] retain] autorelease];
[self removeObjectAtIndex:0];
return queueObject;
}
}
// Add to the tail of the queue
-(void)queuePush:(id)anObject {
@synchronized(self)
{
[self addObject:anObject];
}
}
//Stacks are last-in-first-out.
-(id)stackPop {
@synchronized(self)
{
id lastObject = [[[self lastObject] retain] autorelease];
if (lastObject)
[self removeLastObject];
return lastObject;
}
}
-(void)stackPush:(id)obj {
@synchronized(self)
{
[self addObject: obj];
}
}
@end
要创建和使用队列:
NSMutableArray *queue = [NSMutableArray array];
//Put an item in the queue
[queue queuePush:myObj];
//Retrieve an item, (this will be the first one)
MyCoolObject *myObject = [queue queuePop];
3条答案
按热度按时间rmbxnbpk1#
NSMutableArray上的分类是IMO最简单的方法。我有一个堆栈(LIFO)和队列(FIFO)的分类
标题
执行情况
要创建和使用队列:
xxb16uws2#
FIFO方式的数组:
w3nuxt5m3#
尽管我不理解NSMutableArray的问题,但这里有一种使用双向链表实现队列的方法(希望我没弄错,我有点累了;)):
注意:我假设使用ARC。
如果您正在寻找一种在纯C中实现这一点的方法,也许以下代码会对您有所帮助:
C PROGRAM TO IMPLEMENT A QUEUE