ios实现简易队列
程序员文章站
2022-06-30 10:12:14
本文实例为大家分享了ios实现简易队列的具体代码,供大家参考,具体内容如下满足一些特殊需求接口部分(队列支持需求)#import @int...
本文实例为大家分享了ios实现简易队列的具体代码,供大家参考,具体内容如下
满足一些特殊需求
接口部分(队列支持需求)
#import <foundation/foundation.h> @interface xmqueue : nsobject ///队列追加 - (void)add:(id) obj; ///队列取出 - (id)next; ///返回队列最前端,不删除队列内元素 - (id)first; ///队列内是否还有元素 - (bool) isempty; ///队列转array - (nsarray *) arraycopy; @end
实现方法
#import "xmqueue.h" @interface xmqueue() @property nsmutablearray *array; @property nsinteger currentindex; @end @implementation xmqueue - (instancetype)init { self = [super init]; if (self) { self.array = [[nsmutablearray alloc] initwithcapacity:32]; } return self; } - (void)add:(id) obj{ if (self.currentindex >= self.array.count-1) { nsmutablearray *newarray = [[nsmutablearray alloc] initwithcapacity:self.array.count*2]; for (id obj in self.array) { [newarray addobject:obj]; } self.array = newarray; } [self.array addobject:obj]; } - (id)next{ if (![self isempty]) { id obj = [self.array objectatindex:0]; [self.array removeobjectatindex:0]; return obj; }else{ return @"empty"; } } - (id)first{ if (![self isempty]) { return self.array[0]; }else{ return @"empty"; } } - (bool) isempty{ return self.array.count == 0; } @end
测试
xmqueue *queue = [[xmqueue alloc] init]; for (int i = 0; i < 5; i++) { [queue add:[nsnumber numberwithint:i]]; } for (nsnumber *number in [queue arraycopy]) { printf("%d,",[number intvalue]); } printf("\n"); [queue add:[queue next]]; for (nsnumber *number in [queue arraycopy]) { printf("%d,",[number intvalue]); } printf("\n"); [queue add:[queue next]]; for (nsnumber *number in [queue arraycopy]) { printf("%d,",[number intvalue]); } printf("\n"); [queue add:[queue next]]; for (nsnumber *number in [queue arraycopy]) { printf("%d,",[number intvalue]); } printf("\n"); [queue add:[queue next]]; for (nsnumber *number in [queue arraycopy]) { printf("%d,",[number intvalue]); } printf("\n"); [queue add:[queue next]]; for (nsnumber *number in [queue arraycopy]) { printf("%d,",[number intvalue]); }
结果
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。