iOS 實現(xiàn)一個棧
蘋果的Cocoa并沒有暴露系統(tǒng)的棧結(jié)構(gòu) ,這里根據(jù)棧的特點啦租,使用數(shù)組實現(xiàn)了一個簡單的棧瞬沦。
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]);
輸出結(jié)果:
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)