当前位置 : 主页 > 手机开发 > ios >

ios实现简易队列

来源:互联网 收集:自由互联 发布时间:2021-05-09
本文实例为大家分享了ios实现简易队列的具体代码,供大家参考,具体内容如下 满足一些特殊需求 接口部分(队列支持需求) #import Foundation/Foundation.h@interface XMQueue : NSObject///队列追加-

本文实例为大家分享了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]);
 
 }

结果

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自由互联。

网友评论