题目:
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数appendTail 和deleteHead,分别完成在队列尾部插入结点和在队列头部删除结点的功能。
思路:


解答:
@interface NSCustomQueue : NSObject
// 添加 到 尾部
- (void)appendTail:(id)object;
// 删除 头部
- (BOOL)deleteHeader;
@end
实现文件:
#import "NSCustomStack.h"
#import "NSCustomQueue.h"
@interface NSCustomQueue()
// 入栈 队列
@property (nonatomic, strong) NSCustomStack *pushStack;
// 出栈 队列
@property (nonatomic, strong) NSCustomStack *popStack;
@end
@implementation NSCustomQueue
#pragma mark --------------- Public Methods
// 添加 到 尾部
- (void)appendTail:(id)object {
[self.pushStack push:object];
}
// 删除 头部
- (BOOL)deleteHeader {
if ([self.popStack isEmpty]) {
__weak typeof(self) weakSelf = self;
[self.pushStack traversalElementPopStack:^(id objc) {
[weakSelf.popStack push:objc];
}];
}
if ([self.popStack isEmpty]) {
return NO;
}
[self.popStack popTopElement];
return YES;
}
- (void)printWithBlock:(NSCustomQueueBlock)block {
if (self.popStack.stackLength > 0) {
[self.popStack traversalElementFromtop:^(id objc) {
if (block) {
block(objc);
}
}];
}
if (self.pushStack.stackLength > 0) {
[self.pushStack traversalElementFromBottom:^(id objc) {
if (block) {
block(objc);
}
}];
}
}
#pragma mark --------------- Getter / Setter
// 入栈 队列
- (NSCustomStack *)pushStack {
if(!_pushStack){
_pushStack = [[NSCustomStack alloc] init];
}
return _pushStack;
}
// 出栈 队列
- (NSCustomStack *)popStack {
if(!_popStack){
_popStack = [[NSCustomStack alloc] init];
}
return _popStack;
}
@end
main函数:
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSCustomQueue *customQueue = [[NSCustomQueue alloc] init];
[customQueue appendTail:@"1"];
[customQueue appendTail:@"2"];
[customQueue appendTail:@"3"];
[customQueue deleteHeader];
[customQueue appendTail:@"4"];
[customQueue appendTail:@"5"];
[customQueue printWithBlock:^(id objc) {
NSLog(@"%@", (NSString *)objc);
}];
}
return 0;
}
网友评论