-
-
Notifications
You must be signed in to change notification settings - Fork 359
/
Copy pathStack.cs
80 lines (66 loc) · 1.79 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
using System;
using System.Collections.Generic;
namespace my
{
/**
* implementation using linked list
* [value][next] -> [value][next] -> ... -> [value][next]
* (top Node) (intermediat Nodes)
* left most Node represents top element of stack
*/
public class Node {
public Node next;
public object data;
}
public class Stack {
private Node head;
public int size;
public Stack() {
head = new Node();
size = 0;
}
public void Push(object value) {
Node newNode = new Node();
newNode.data = value;
newNode.next = head.next;
head.next = newNode;
size++;
}
public void Pop() {
if (size != 0) {
head.next = head.next.next;
size--;
}
else {
Console.WriteLine("No element to remove.");
}
}
public object Top() {
return head.next.data;
}
public int Size() {
return size;
}
public bool Empty() {
return size == 0;
}
}
class Test {
static void Main(string[] args) {
Console.WriteLine("Stack:");
Stack intStack = new Stack();
intStack.Push(4);
intStack.Push(5);
intStack.Push(9);
Console.Write("Size: ");
Console.WriteLine(intStack.Size());
Console.Write("Top: ");
Console.WriteLine(intStack.Top());
intStack.Pop();
Console.Write("Size: ");
Console.WriteLine(intStack.Size());
Console.Write("Top: ");
Console.WriteLine(intStack.Top());
}
}
}