Skip to content

Instantly share code, notes, and snippets.

@kavitshah8
Last active January 11, 2016 15:46
Show Gist options
  • Save kavitshah8/aa3885d5cf5cc8aeea48 to your computer and use it in GitHub Desktop.
Save kavitshah8/aa3885d5cf5cc8aeea48 to your computer and use it in GitHub Desktop.
Stack
'use strict';
function stepsToSolveHanoiT(height, srcP, desP, bufferP) {
if (height >= 1) {
// Move a tower of height-1 to the buffer peg, using the destination peg.
stepsToSolveHanoiT(height - 1, srcP, bufferP, desP);
// Move the remaining disk to the destination peg.
console.log('Move disk from Tower ', srcP, ' to Tower ', desP);
// Move the tower of `height-1` from the `buffer peg` to the `destination peg` using the `source peg`.
stepsToSolveHanoiT(height - 1, bufferP, desP, srcP);
}
return;
}
stepsToSolveHanoiT(3, "A", "C", "B");
// Move disk from Tower A to Tower C
// Move disk from Tower A to Tower B
// Move disk from Tower C to Tower B
// Move disk from Tower A to Tower C
// Move disk from Tower B to Tower A
// Move disk from Tower B to Tower C
// Move disk from Tower A to Tower C
'use strict';
function Queue () {
this.pushS = new Stack();
this.popS = new Stack();
}
Queue.prototype.enqueue = function (val) {
this.pushS.push(val);
};
Queue.prototype.dequeue = function () {
var poping = this.popS;
var pushing = this.pushS;
if (poping.top) {
var deq = poping.pop();
console.log('Dequeing ' + deq + ' from stack.');
return deq;
}
while (pushing.top) {
poping.push(pushing.pop());
}
};
var q1 = new Queue();
q1.enqueue(3);
q1.enqueue(4);
q1.enqueue(5);
q1.enqueue(6);
q1.enqueue(7);
q1.dequeue();
q1.dequeue();
q1.dequeue();
console.log('Current stat of the Queue is stored saved in the popS.');
console.log(q1);
'use strict';
function Stack() {
this.top = null;
}
Stack.prototype.sort = function() {
var s2 = new Stack();
while (this.top) {
var tmp = this.pop();
while (s2.top && s2.top.data > tmp) {
s1.push(s2.pop());
}
s2.push(tmp);
}
console.log('Sorted stack = ', s2);
}
var s1 = new Stack();
s1.push(3);
s1.push(6);
s1.push(1);
s1.push(2);
s1.push(5);
s1.push(4);
s1.sort();
'use strict';
function Stack() {
this.top = null;
}
Stack.prototype.push = function (val) {
this.top = {
data : val,
next : this.top
};
};
Stack.prototype.pop = function () {
var top = this.top;
if (top) {
var popData = top.data;
top = top.next;
return popData;
}
return;
};
var S1 = new Stack();
S1.push(5);
S1.push(6);
S1.push(7);
S1.push(8);
console.log(S1.pop()); // 8
console.log(S1.pop()); // 7
console.log(S1); // Stack {top: Object}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment