using Stack_3102; /* * Stack Data Structure for CSC 3102 Protfolio * Using Linked List as underlying imlementation * using Stype */ /* * --REQUIRED METHODS-- * Stack() * Push(Stype item) * Stype Pop() * Stype Peek() * Size() * --OPTIONAL METHODS-- * bool isEmpty() * override ToString() or printArray() */ namespace Stack_3102 { public class StackNode { public T? data; public StackNode? prev; public StackNode() { data = default; prev = null; } public StackNode(T value, StackNode? prev = null) { this.data = value; this.prev = prev; } } public class Stack { public StackNode? top; public int size; //default constructor public Stack() { top = null; size = 0; } /* * Adds a new node to the top of the stack * @item - the data you are adding */ public void Push(Stype item) { if (top == null) { var newTop = new StackNode(item); top = newTop; } else { var newNode = new StackNode(item, top); top = newNode; } size++; } /* * Removes the node at the top of the stack */ public Stype Pop() { if (top == null) { throw new Exception("Stack is empty"); } var remItem = top.data; top = top.prev; size--; return remItem; } /* * Returns the data at the top of the stack */ public Stype Peek() { if (top == null) { throw new Exception("There is no top value, bc stack is empty"); } return top.data; } //returns the size of the stack public int Size() { return size; } bool isEmpty() { if (top == null) { return true; } else { return false; } } //prints the stack, starting with the top value public void PrintStack() { if (this.isEmpty()) { Console.WriteLine("The stack is empty"); return; } var travNode = this.top; Console.Write("["); for (int i = 0; i < size; i++) { if (travNode.data != null) { Console.Write(travNode.data + " "); } travNode = travNode.prev; } Console.WriteLine("]"); Console.WriteLine("Printed from the top down"); } } }