我在Objective-C中实现了一个堆栈,当我测试我的类时,我得到了无效的结果。 以下是代码:
类别/ Stack.h:
#import <Foundation/Foundation.h>
#define DEFAULT_SIZE 16
@interface Stack : NSObject {
@private int size;
@private int top;
@private NSMutableArray* arr;
}
- (id) init;
- (id) initWithSize: (int) size;
- (void) push: (id) element;
- (id) pop;
- (id) peek;
- (int) size;
- (BOOL) isEmpty;
@end
类别/ Stack.m:
#import "Stack.h"
@implementation Stack
- (id) init {
self = [super init];
if(self) {
size = DEFAULT_SIZE;
top = 0;
arr = [[NSMutableArray alloc] init];
}
return self;
}
- (id) initWithSize: (int) aSize {
self = [super init];
if(self) {
if(aSize <= 0)
@throw [NSException exceptionWithName:@"Invalid Argument" reason:@"Size should be strictly positive." userInfo:nil];
size = aSize;
top = 0;
arr = [[NSMutableArray alloc] init];
}
return self;
}
- (void) push: (id) element {
if(top > size)
@throw [NSException exceptionWithName:@"Illegal State" reason:@"Stack contents exceed the valid limit." userInfo:nil];
if(top == size)
@throw [NSException exceptionWithName:@"Stack Overflow" reason:@"Stack is full, can not push any element." userInfo:nil];
[arr addObject:element];
top++;
}
- (id) pop {
if(top < 0)
@throw [NSException exceptionWithName:@"Illegal State" reason:@"Stack lower limit is invalid." userInfo:nil];
if(top == 0)
@throw [NSException exceptionWithName:@"Stack Underflow" reason:@"Stack is empty, can not pop any element" userInfo:nil];
// id ret = [arr lastObject];
// [arr removeLastObject];
// top--;
id ret = [arr objectAtIndex:(--top)];
return ret;
}
- (id) peek {
if(top < 0)
@throw [NSException exceptionWithName:@"Illegal State" reason:@"Stack lower limit is invalid." userInfo:nil];
if(top == 0)
@throw [NSException exceptionWithName:@"Stack Underflow" reason:@"Stack is empty, can not pop any element" userInfo:nil];
// return [arr lastObject];
return [arr objectAtIndex:(top - 1)];
}
- (int) size {
return top;
}
- (BOOL) isEmpty {
return top == 0;
}
@end
和main.m:
#import <Foundation/Foundation.h>
#import "Classes/Stack.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Stack* stack = [[Stack alloc] initWithSize:3];
[stack push:@"world"];
[stack push:@" "];
[stack push:@"hello"];
for(int i = 0; i < [stack size]; i++)
NSLog(@"%@", [stack pop]);
}
return 0;
}
我得到的结果是:
2014-01-07 00:09:36.045 Data Structures[9210:303] hello
2014-01-07 00:09:36.047 Data Structures[9210:303]
Program ended with exit code: 0
我的代码有问题并产生无效结果吗?
答案 0 :(得分:3)
好的,让我们走一圈。
i == 0
[stack size] == 3
i == 1
[stack size] == 2
i == 2
[stack size] == 1
因此循环在第三次迭代之前停止。
您希望循环看起来像下列之一:
int stackSize = [stack size];
for (int i = 0; i < stackSize; i++)
NSLog(@"%@", [stack pop]);
}
或
while ([stack size] > 0) {
NSLog(@"%@", [stack pop]);
}
顺便提一下,正如其他几个人所指出的那样,你并不真正需要top
- 它只是你数组计数的重复。但即使有这种变化,循环中也会出现相同的逻辑错误。