且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

算法-链表实现队列

更新时间:2022-09-16 17:50:13

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

Node定义:

1
2
3
4
5
6
7
@interface Node : NSObject
 
@property  (strong,nonatomic)  NSString  *value;
 
@property  (strong,nonatomic)  Node  *next;
 
@end

Queue.h文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@interface Queue : NSObject
 
//最先入列的元素
@property  (strong,nonatomic) Node  *first;
 
//最后入列的元素
@property  (strong,nonatomic)  Node  *last;
 
@property  (assign,nonatomicNSInteger  count;
 
-(BOOL)isEmpty;
 
-(NSInteger)size;
 
-(void)enqueue:(NSString *)value;
 
-(NSString *)dequeue;
 
-(void)remove:(NSString *)value;
 
@end

Queue.m代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
@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

 调用如下:

1
2
3
4
5
6
7
8
9
10
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);

输出如下:

算法-链表实现队列

本文转自Fly_Elephant博客园博客,原文链接:http://www.cnblogs.com/xiaofeixiang/p/4562146.html,如需转载请自行联系原作者