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
网友评论