本文实例为大家分享了ios实现简易队列的具体代码,供大家参考,具体内容如下
满足一些特殊需求
接口部分(队列支持需求)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
#import <foundation/foundation.h> @interface xmqueue : nsobject ///队列追加 - ( void )add:(id) obj; ///队列取出 - (id)next; ///返回队列最前端,不删除队列内元素 - (id)first; ///队列内是否还有元素 - ( bool ) isempty; ///队列转array - (nsarray *) arraycopy; @end |
实现方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
#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 |
测试
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
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]); } |
结果
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/qq_41586150/article/details/104385727