-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDCStack.m
More file actions
78 lines (62 loc) · 1.25 KB
/
DCStack.m
File metadata and controls
78 lines (62 loc) · 1.25 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
//
// DCStack.m
// DC Standard Library
//
// Created by Dalmo Cirne on 5/28/13.
// Copyright (c) 2013 Dalmo Cirne. All rights reserved.
//
#import "DCStack.h"
#import "DCNode.h"
#import <dispatch/dispatch.h>
@interface DCStack() {
DCNode *topNode;
dispatch_queue_t queue;
}
@end
@implementation DCStack
- (id)init {
self = [super init];
if (!self) {
return nil;
}
queue = dispatch_queue_create("com.dalmocirne.Stack", DISPATCH_QUEUE_SERIAL);
_empty = YES;
_count = 0;
_top = nil;
return self;
}
- (void)dealloc {
while (!_empty) {
[self pop];
}
}
- (void)push:(id)object {
if (!object) {
return;
}
dispatch_sync(queue, ^{
DCNode *node = [[DCNode alloc] initWithObject:object];
node.next = topNode;
topNode = node;
++_count;
_empty = NO;
_top = object;
});
}
- (id)pop {
if (_empty) {
return nil;
}
__block id object = nil;
dispatch_sync(queue, ^{
DCNode *node = topNode;
topNode = topNode.next;
node.next = nil;
object = node.object;
--_count;
_empty = _count == 0;
_top = topNode.object;
});
return object;
}
@end