comparison core/tools/CStack.m @ 0:e9a9cd732c1e tip

first hg version after svn
author wolffd
date Tue, 10 Feb 2015 15:05:51 +0000
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:e9a9cd732c1e
1 classdef CStack < handle
2 % CStack define a stack data strcuture
3 %
4 % It likes java.util.Stack, however, it could use CStack.content() to
5 % return all the data (in cells) of the Stack, and it is a litter faster
6 % than java's Stack.
7 %
8 % s = CStack(c); c is a cells, and could be omitted
9 % s.size() return the numble of element
10 % s.isempty() return true when the stack is empty
11 % s.empty() delete the content of the stack
12 % s.push(el) push el to the top of stack
13 % s.pop() pop out the top of the stack, and return the element
14 % s.top() return the top element of the stack
15 % s.remove() remove all the elements in the stack
16 % s.content() return all the data of the stack (in the form of a
17 % cells with size [s.size(), 1]
18 %
19 % See also CList, CQueue
20 %
21 % Copyright: zhang@zhiqiang.org, 2010.
22 % url: http://zhiqiang.org/blog/it/matlab-data-structures.html
23
24 properties (Access = private)
25 buffer % 一个cell数组,保存栈的数据
26 cur % 当前元素位置, or the length of the stack
27 capacity % 栈的容量,当容量不够时,容量扩充为2倍。
28 end
29
30 methods
31 function obj = CStack(c)
32 if nargin >= 1 && iscell(c)
33 obj.buffer = c(:);
34 obj.cur = numel(c);
35 obj.capacity = obj.cur;
36 elseif nargin >= 1
37 obj.buffer = cell(100, 1);
38 obj.cur = 1;
39 obj.capacity =100;
40 obj.buffer{1} = c;
41 else
42 obj.buffer = cell(100, 1);
43 obj.capacity = 100;
44 obj.cur = 0;
45 end
46 end
47
48 function s = size(obj)
49 s = obj.cur;
50 end
51
52 function remove(obj)
53 obj.cur = 0;
54 end
55
56 function b = empty(obj)
57 b = obj.cur;
58 obj.cur = 0;
59 end
60
61 function b = isempty(obj)
62 b = ~logical(obj.cur);
63 end
64
65 function push(obj, el)
66 if obj.cur >= obj.capacity
67 obj.buffer(obj.capacity+1:2*obj.capacity) = cell(obj.capacity, 1);
68 obj.capacity = 2*obj.capacity;
69 end
70 obj.cur = obj.cur + 1;
71 obj.buffer{obj.cur} = el;
72 end
73
74 function el = top(obj)
75 if obj.cur == 0
76 el = [];
77 warning('CStack:No_Data', 'trying to get top element of an emtpy stack');
78 else
79 el = obj.buffer{obj.cur};
80 end
81 end
82
83 function el = pop(obj)
84 if obj.cur == 0
85 el = [];
86 warning('CStack:No_Data', 'trying to pop element of an emtpy stack');
87 else
88 el = obj.buffer{obj.cur};
89 obj.cur = obj.cur - 1;
90 end
91 end
92
93 function display(obj)
94 if obj.cur
95 for i = 1:obj.cur
96 disp([num2str(i) '-th element of the stack:']);
97 disp(obj.buffer{i});
98 end
99 else
100 disp('The stack is empty');
101 end
102 end
103
104 function c = content(obj)
105 c = obj.buffer(1:obj.cur);
106 end
107 end
108 end