File tree Expand file tree Collapse file tree
source/code/projects/CAStack/CAStack Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ using System ;
2+
3+ class CAStack < T >
4+ {
5+
6+ private T [ ] mArray ;
7+ // Contains the number of the next empty cell.
8+ private int top = 0 ;
9+
10+ // Our default stack size is 10.
11+ public CAStack ( int sizeP = 10 )
12+ {
13+ if ( sizeP <= 0 )
14+ throw new ApplicationException ( "Stack size must be strictly greater than 0." ) ;
15+ else
16+ mArray = new T [ sizeP ] ;
17+ }
18+
19+ public void Clear ( )
20+ {
21+ top = 0 ;
22+ }
23+
24+ public bool IsEmpty ( )
25+ {
26+ return top == 0 ;
27+ }
28+
29+ public void Push ( T value )
30+ {
31+ if ( top < mArray . Length )
32+ {
33+ mArray [ top ] = value ;
34+ top ++ ;
35+ }
36+ else
37+ {
38+ throw new ApplicationException ( "Stack is full." ) ;
39+ }
40+ }
41+
42+ public T Pop ( )
43+ {
44+ if ( IsEmpty ( ) )
45+ throw new ApplicationException (
46+ "An empty stack cannot be popped."
47+ ) ;
48+ return mArray [ -- top ] ;
49+ }
50+
51+
52+ public T Peek ( )
53+ {
54+ if ( IsEmpty ( ) )
55+ throw new ApplicationException (
56+ "An empty stack cannot be peeked."
57+ ) ;
58+ return mArray [ top - 1 ] ;
59+ }
60+
61+ public int Count
62+ {
63+ get
64+ {
65+ return top ;
66+ }
67+ }
68+
69+
70+ public override string ToString ( )
71+ {
72+ string returned = "" ;
73+ if ( ! IsEmpty ( ) )
74+ {
75+ int counter = top - 1 ;
76+ while ( counter >= 0 )
77+ {
78+ if ( returned . Length > 0 )
79+ returned += ":" ;
80+ returned += mArray [ counter ] ;
81+ counter -- ;
82+ }
83+ }
84+ return returned ;
85+
86+ }
87+
88+ }
Original file line number Diff line number Diff line change 1+ using System ;
2+
3+ class Program
4+ {
5+ static void Main ( string [ ] args )
6+ {
7+ /* First example. */
8+ CAStack < int > myStack1 = new CAStack < int > ( ) ;
9+ Console . WriteLine ( myStack1 ) ;
10+ myStack1 . Push ( 1 ) ;
11+ myStack1 . Push ( 5 ) ;
12+ myStack1 . Push ( 2 ) ;
13+ myStack1 . Push ( 2 ) ;
14+ myStack1 . Push ( 1 ) ;
15+ myStack1 . Push ( 1 ) ;
16+ myStack1 . Push ( 3 ) ;
17+ myStack1 . Push ( 4 ) ;
18+ myStack1 . Push ( 5 ) ;
19+ myStack1 . Push ( 5 ) ;
20+ try
21+ {
22+ myStack1 . Push ( 5 ) ;
23+ } catch ( Exception ex )
24+ {
25+ Console . WriteLine ( ex . Message ) ;
26+ }
27+ Console . WriteLine ( myStack1 ) ;
28+
29+ /* Second example. */
30+ CAStack < char > myStack2 = new CAStack < char > ( ) ;
31+ try
32+ {
33+ myStack2 . Pop ( ) ;
34+ }
35+ catch ( Exception ex )
36+ {
37+ Console . WriteLine ( ex . Message ) ;
38+ }
39+ try
40+ {
41+ myStack2 . Peek ( ) ;
42+ }
43+ catch ( Exception ex )
44+ {
45+ Console . WriteLine ( ex . Message ) ;
46+ }
47+
48+ myStack2 . Push ( 'a' ) ;
49+ myStack2 . Push ( 'z' ) ;
50+ Console . WriteLine (
51+ "Value at top of stack: " + myStack2 . Peek ( )
52+ ) ;
53+ }
54+ }
You can’t perform that action at this time.
0 commit comments