我在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
我的代码有什么问题并产生无效的结果吗?
好的,让我们遍历循环。
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
-它只是阵列数量的重复。但是即使更改,相同的逻辑错误也会出现在循环中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句