iOS 实现一个栈
苹果的Cocoa并没有暴露系统的栈结构 ,这里根据栈的特点,使用数组实现了一个简单的栈。
MyStack.h
@interface MyStack : NSObject
- (void)push:(id)obj;
- (id)pop;
- (id)peek;
@end
MyStack.m
#import "MyStack.h"
// 定义栈的容量
#define kStackSize 10
@interface MyStack ()
@property (nonatomic, strong) NSMutableArray *list;
@property (nonatomic, assign) NSInteger size; // the number of stack elements
@end
@implementation MyStack
- (instancetype)init
{
self = [super init];
if (self) {
self.list = [NSMutableArray arrayWithCapacity:kStackSize];
self.size = 0;
}
return self;
}
- (void)push:(id)obj
{
if ([self isFull] || !obj) return;
[self.list addObject:obj];
self.size++;
}
- (id)pop
{
if ([self isEmpty]) return nil;
id obj = [self.list objectAtIndex:self.size -1];
[self.list removeObjectAtIndex:self.size - 1];
self.size--;
return obj;
}
- (id)peek
{
if ([self isEmpty]) return nil;
id obj = [self.list objectAtIndex:self.size -1];
return obj;
}
- (BOOL)isEmpty
{
return self.size == 0;
}
- (BOOL)isFull
{
return self.size == kStackSize;
}
@end
线程安全的 MyStack.m
#import "MyStack.h"
#define kStackSize 10
@interface MyStack ()
@property (nonatomic, strong) NSMutableArray *list;
@property (nonatomic, assign) NSInteger size; // the number of stack elements
@property (nonatomic, strong) dispatch_semaphore_t semaphore; // 信号量 锁
@end
@implementation MyStack
- (instancetype)init
{
self = [super init];
if (self) {
self.list = [NSMutableArray arrayWithCapacity:kStackSize];
self.size = 0;
self.semaphore = dispatch_semaphore_create(1);
}
return self;
}
- (void)push:(id)obj
{
if ([self isFull] || !obj) return;
dispatch_semaphore_wait(self.semaphore, DISPATCH_TIME_FOREVER);
[self.list addObject:obj];
self.size++;
dispatch_semaphore_signal(self.semaphore);
}
- (id)pop
{
if ([self isEmpty]) return nil;
dispatch_semaphore_wait(self.semaphore, DISPATCH_TIME_FOREVER);
id obj = [self.list objectAtIndex:self.size -1];
[self.list removeObjectAtIndex:self.size - 1];
self.size--;
dispatch_semaphore_signal(self.semaphore);
return obj;
}
- (id)peek
{
if ([self isEmpty]) return nil;
id obj = [self.list objectAtIndex:self.size -1];
return obj;
}
- (BOOL)isEmpty
{
return self.size == 0;
}
- (BOOL)isFull
{
return self.size == kStackSize;
}
@end
测试代码
MyStack *stack = [[MyStack alloc] init];
[stack push:@(1)];
[stack push:@(2)];
[stack push:@(3)];
NSLog(@"%@", [stack peek]);
NSLog(@"%@", [stack pop]);
NSLog(@"%@", [stack pop]);
NSLog(@"%@", [stack pop]);
NSLog(@"%@", [stack pop]);
输出结果:
2022-01-02 21:52:04.782525+0800 MyStack[15061:347654] 3
2022-01-02 21:52:04.783088+0800 MyStack[15061:347654] 3
2022-01-02 21:52:04.783163+0800 MyStack[15061:347654] 2
2022-01-02 21:52:04.783226+0800 MyStack[15061:347654] 1
2022-01-02 21:52:04.783247+0800 MyStack[15061:347654] (null)