算法-链表实现栈
发布时间:2020-12-16 07:45:30 所属栏目:百科 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 原文? http://www.cnblogs.com/xiaofeixiang/p/4558408.html @interface Node : NSObject@property (strong,nonatomic) NSString *value;@property (s
以下代码由PHP站长网 52php.cn收集自互联网 现在PHP站长网小编把它分享给大家,仅供参考
原文?
http://www.cnblogs.com/xiaofeixiang/p/4558408.html
@interface Node : NSObject @property (strong,nonatomic) NSString *value; @property (strong,nonatomic) Node *next; @end Stack头文件定义: @interface Stack : NSObject //栈顶的元素 @property (strong,nonatomic) Node *first; @property (assign,nonatomic) NSInteger count; -(BOOL)isEmpty; -(NSInteger)size; -(void)push:(NSString *)value; -(NSString *)pop; -(void)remove:(NSString *)value; @end @implementation Stack -(BOOL)isEmpty{ return self.count==0; } -(NSInteger)size{ return self.count; } -(void)push:(NSString *)value{ Node *oldFirst=self.first; self.first=[[Node alloc]init]; self.first.value=value; self.first.next=oldFirst; self.count=self.count+1; } -(NSString *)pop{ if (!self.first) { return [NSString stringWithFormat:@"-1"]; } NSString *value=self.first.value; self.first=self.first.next; self.count=self.count-1; return value; } -(void)remove:(NSString *)value{ if ([self.first.value isEqualToString:value]) { Node *node=self.first; Node *nextNode=node.next; node.value=nextNode.value; node.next=nextNode.next; self.count=self.count-1; }else{ Node *node=self.first; while (node.next) { if ([node.next.value isEqualToString:value]){ if (node.next.next) { Node *tempNode=node.next.next; node.next=tempNode; }else{ node.next=NULL; } self.count=self.count-1; break; }else{ node=node.next; } } } } @end 测试代码: tack *stack=[[Stack alloc]init]; Node *first=[[Node alloc]init]; [email?protected]"iOS技术交流群:228407086"; first.next=NULL; stack.first=first; [stack push:@"FlyElephant"]; [stack push:@"博客园"]; [stack push:@"keso"]; [stack remove:@"FlyElephant"]; NSLog(@"出栈:%@",stack.pop); NSLog(@"出栈:%@",stack.pop); 以上内容由PHP站长网【52php.cn】收集整理供大家参考研究 如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |