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