-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathStack.cs
127 lines (100 loc) · 2.82 KB
/
Stack.cs
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Stack
{
class StackVaciaException : Exception { }
class Stack<Item>
{
/*************by:
Gabriel Mendez Reyes -***************/
private Item[] arr;
public int size { get; private set; }
public Stack()
{
size = 0;
arr = new Item[1];
}
public void Push(Item value)
{
if (size == arr.Length)
{
const int FACTOR_CRECIMIENTO = 2;
Resize(arr.Length * FACTOR_CRECIMIENTO);
}
arr[size] = value;
size++;
}
public Item Peek()
{
if (size == 0)
{
throw new StackVaciaException();
}
return arr[size - 1];
}
public Item Pop()
{
if (size == 0)
{
throw new StackVaciaException();
}
Item ret = arr[size - 1];
size--;
if (size * 4 <= arr.Length)
{
const int FACTOR_DECREMENTO = 2;
Resize(arr.Length / FACTOR_DECREMENTO);
}
return ret;
}
public bool isEmpty()
{
return size == 0;
}
public void Resize(int newCapacity)
{
Item[] newArr = new Item[newCapacity];
for (int i = 0; i < size; i++)
{
newArr[i] = arr[i];
}
arr = newArr;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size; i++)
{
sb.Append(arr[i] + " ");
}
return sb.ToString();
}
}
class Program
{
static void Main(string[] args)
{
Stack<int> s1 = new Stack<int>();
s1.Push(3);
s1.Push(4);
Console.WriteLine("Size = {0} , Stack: {1}", s1.size, s1);
s1.Push(5);
s1.Push(6);
Console.WriteLine("Size = {0} , Stack: {1}", s1.size, s1);
s1.Pop();
s1.Pop();
s1.Pop();
Console.WriteLine("Size = {0} , Stack: {1}", s1.size, s1);
/*
Resultado esperado:
.Find(123): ciento veinte y tres
.Remove(123): ciento veinte y tres
.KeyNotFoundException : "123 no existe como key"
.Find(-123) : negativo ciento veinte y tres
*/
}
}
}