p5.js | Push Operation on Stack
Last Updated :
11 Apr, 2023
What is Stack?
The stack is a linear data structure like an array in which only the last inserted element can be accessed. This data structure works over the principle of Last In First Out (LIFO). It is very fast since it has to access only the last added element so it requires constant time to do so having complexity O(1).
Stacks should be used over arrays when we need to work with data in the LIFO form. Push operation on the stack is used to add an item to the stack. If the stack is full, then it is said to be an Overflow condition.
The basic skeleton of the stack: Below example runs using the “$node skeleton.js” command to get the basic stack skeleton.
javascript
function Stack(array) {
this .array = [];
if (array) this .array = array;
}
Stack.prototype.getBuffer = function () {
return this .array.slice();
}
Stack.prototype.isEmpty = function () {
return this .array.length == 0;
}
let stack1 = new Stack();
console.log(stack1);
|
Example: This example describes the push operation on the stack.
javascript
<!DOCTYPE html>
<html>
<head>
<title>Stack push operation</title>
<meta charset= "UTF-8" >
<style>
body {
padding: 0;
margin: 0;
}
canvas {
vertical-align: top;
}
</style>
</head>
<title>
<script>
function Stack(array) {
this .array = [];
if (array) this .array = array;
}
Stack.prototype.getBuffer = function () {
return this .array.slice();
}
Stack.prototype.isEmpty = function () {
return this .array.length == 0;
}
let stack1 = new Stack();
Stack.prototype.push = function (value) {
this .array.push(value);
}
function setup() {
createCanvas(displayWidth, 300);
}
function draw() {
background( "grey" );
strokeWeight(3);
stroke( 'black' );
line(10, 45, 90, 45);
rect(10, 30, 40, 30);
noStroke();
text( "TOP" , 20, 50);
for (let i = stack1[ 'array' ].length - 1; i >= 0; i--) {
let p = 10;
translate(70, 0);
strokeWeight(3);
stroke( 'black' );
line(10 + p, 45, p + 80, 45);
noStroke();
rect(10 + p, 30, 40 + p, 30);
text(stack1[ 'array' ][i], 40, 50);
p += 10;
}
}
stack1.push(1);
stack1.push(2);
stack1.push(3);
stack1.push(19);
stack1.push(11);
stack1.push(12);
</script>
</body>
</html>
|
Output:
After Pushing ’14’ by calling stack1.push(14) function to the top of the stack.
Share your thoughts in the comments
Please Login to comment...