新建一个Stack栈,用来对数组进行操作
@interface Stack : NSObject
- (NSInteger)pop;
- (void)push:(NSInteger)number;
- (BOOL)isOperator:(NSString *)str;
@property(nonatomic, strong)NSMutableArray *stack;
@end
@implementation Stack
- (instancetype)init
{
self = [super init];
if (self) {
_stack = [NSMutableArray array];
}
return self;
}
- (NSInteger)pop
{
if (_stack.count > 0){
NSInteger lastNumber = ((NSNumber *)(_stack.lastObject)).integerValue;
[_stack removeLastObject];
return lastNumber;
}
return (long)0;
}
- (void)push:(NSInteger)number
{
[_stack addObject:[[NSNumber alloc]initWithInteger:number]];
}
- (BOOL)isOperator:(NSString *)str{
return [@"+-*/" containsString:str];
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
//逆波兰算法
NSArray *opArray = @[@"10", @"6", @"9", @"3", @"+", @"-11", @"*", @"/", @"*", @"17", @"+", @"5", @"+"];
Stack *stack = [[Stack alloc] init];
NSInteger result = 0;
for (NSString *str in opArray)
{
if ([stack isOperator:str] == NO)
{
[stack push:str.integerValue];
}else {
NSInteger leftOperator = result == 0 ? [stack pop] : result;
NSInteger rightOperator = [stack pop];
if ([str isEqualToString:@"+"]){
result = rightOperator+leftOperator;
}else if ([str isEqualToString:@"-"]){
result = rightOperator-leftOperator;
}else if ([str isEqualToString:@"*"]){
result = rightOperator*leftOperator;
}else{
result = rightOperator/leftOperator;
}
}
}
NSLog(@"");
}
@end
网友评论