OC_链表实现队列
- @interface Node : NSObject
- @property(nonatomic,strong)NSString *value;
- @property(nonatomic,strong)Node *next;
Queue的头文件内容:
- #import <Foundation/Foundation.h>
- @class Node;
- @interface Queue : NSObject
- @property (strong,nonatomic) Node *first;
- @property (strong,nonatomic) Node *last;
- @property (assign,nonatomic) NSInteger count;
- -(BOOL)isEmpty;
- -(NSInteger)size;
- -(void)enqueue:(NSString *)value;
- -(NSString *)dequeue;
- -(void)remove:(NSString *)value;
- @end
- Queue的实现内容:
- #import "Queue.h"
- #import "Node.h"
- @implementation Queue
- -(BOOL)isEmpty{
- return self.count==0;
- }
- -(NSInteger)size{
- return self.count;
- }
- -(void)enqueue:(NSString *)value{
- Node *oldLast=self.last;
- self.last=[[Node alloc]init];
- self.last.data=value;
- self.last.next=NULL;
- oldLast.next=self.last;
- if ([self isEmpty]) {
- self.first=self.last;
- }else{
- oldLast.next=self.last;
- }
- self.count=self.count+1;
- }
- -(NSString *)dequeue{
- if ([self isEmpty]) {
- return [NSString stringWithFormat:@"-1"];
- }
- NSString *result=self.first.data;
- self.first=self.first.next;
- self.count=self.count-1;
- return result;
- }
- -(void)remove:(NSString *)value{
- //判断是不是头部节点
- if ([self.first.data isEqualToString:value]) {
- self.first=self.first.next;
- self.count=self.count-1;
- }else
- {
- Node *node=self.first;
- while (node!=NULL)
- {
- if ([node.next.data isEqualToString:value])
- {
- node.next=node.next.next;
- self.count=self.count-1;
- break;
- }
- node=node.next;
- }
- }
- }
- @end