COP3530 Assignment 5 - The Stack

by joseph_kanawall2400

HTML

<input type="textbox" id="item_tb" />
<input type="button" id="push_button" value="Push to Stack" onClick="pushToStack();" />
<br/> Contents of Stack:
<div id="stack_div"></div>
<br/><br/>
In order to create the tetris like game, you would need a double linked list that is made up of double linked lists. Stacks are an option if you want to pop and push every node in the stack on every game loop where a number/operation stops moving. I would opt for a list since I could pull the list node per index and have the checks per row, meaning I would not have to remove and add every node in every list, unlike a stack would. Once I convert a row into a linked list, then for each node, I could check the last and next nodes, and compare their values.

JavaScript

// Node
var Node = function (value, last) {
    this.next = null;
    this.last = last;
    this.value = value;
}

// Stack
var Stack = function() {
    this.head = null;
    this.top = null;
	this.size = 0;
	
    this.push = function(value) {
		if(this.head == null) {
			this.head = new Node(value, null);
			this.top = this.head;
		}
		else
		{
			var newNode = new Node(value, this.top);
			this.top.next = newNode;
			this.top = newNode;			
		}
		this.size++;
		return this;
    }
	
	this.pop = function() {
		var oldTop = this.top;
		if(this.top != null) {
			if(this.top.last == null) {
				this.top = null;
				this.head = null;
			}
			else
			{
				this.top = this.top.last;
				this.top.next = null;
			}
			this.size--;
		}
		return oldTop;
	}

	this.print = function() {
		var string = "";
		var node = this.top;
		
		if(node == null) {
			string = "There are no Nodes in the Stack.";
		}
		else
		{
			while(node != null) {
				string += node.value + " ";
				node = node.last;
			}
		}
		return string;
	}
}

// Other Functions
document.getElementById("item_tb").addEventListener("keyup", function(event) {
    event.preventDefault();
    if (event.keyCode == 13) {
        document.getElementById("push_button").click();
    }
});

function pushToStack() {
	var item = document.getElementById('item_tb');
	
	if(isNaN(item.value)){
		if(!(item.value == "+" || item.value == "-" || item.value == "*" || item.value == "/")) {
			alert("Please enter a valid number or +, -, *, /");
		}
		else
		{
			if(stack.size < 2) {
				alert("There are not enough numbers in the stack to do a calculation.");
			}
			else {
				var num1 = stack.pop().value;
				var num2 = stack.pop().value;
				stack.push(eval(num2 + " " + item.value + " " + num1))
			}
		}
	}
	else {
		stack.push(item.value);
	}
	
	document.getElementById('stack_div').innerHTML = stack.print();
	item.value = "";
	item.focus();
}

var stack = new Stack();