# 算法-链表实现栈

Node定义:

```@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
```

Stack.m的实现代码:

```@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]) {
self.first=self.first.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
```

```        Stack  *stack=[[Stack alloc]init];
Node *first=[[Node alloc]init];
first.value=@"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);
NSLog(@"出栈:%@",stack.pop);
NSLog(@"出栈:%@",stack.pop);
```

原文作者：Fly_Elephant
原文地址: https://www.cnblogs.com/xiaofeixiang/p/4558408.html
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。