算法-链表实现队列

队列和栈是最常用的数据结构,跟栈不同的是栈是先进后出,队列是先进先出,生活中简单的队列的例子比如说排队买票,排队等公交,具体的原理可以参考网上,基本上大同小异,本文简单的实现一下队列的入列,出列和删除的操作,跟栈一样,队列是通过Node关联操作,具体实现如下:

Node定义:

@interface Node : NSObject

@property  (strong,nonatomic)  NSString  *value;

@property  (strong,nonatomic)  Node  *next;

@end

Queue.h文件:

@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.m代码:

@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.value=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.value;
    self.first=self.first.next;
    self.count=self.count-1;
    return result;
}

-(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!=NULL) {
            if ([node.next.value isEqualToString:value]) {
                node.next=node.next.next;
                self.count=self.count-1;
                break;
            }
            node=node.next;
        }
    }
}
@end

 调用如下:

        Queue  *queue=[[Queue alloc]init];
        [queue enqueue:@"iOS技术交流群:228407086"];
        [queue enqueue:@"FlyElephant"];
        [queue enqueue:@"博客园"];
        [queue enqueue:@"keso"];
        [queue remove:@"keso"];
        NSLog(@"出队列:%@",queue.dequeue);
        NSLog(@"出队列:%@",queue.dequeue);
        NSLog(@"出队列:%@",queue.dequeue);
        NSLog(@"出队列:%@",queue.dequeue);

输出如下:

posted @ 2015-06-08 22:29  Fly_Elephant  阅读(1104)  评论(0编辑  收藏  举报