Created
July 25, 2020 04:57
-
-
Save Lugriz/cf88ee80d15aeb377b5d8cf4fd7ce4bc to your computer and use it in GitHub Desktop.
Stack implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Nodo { | |
public next: Nodo = null; | |
constructor( | |
public value: number | |
) {} | |
} | |
class Stack { | |
private head: Nodo = null; | |
private length: number = 0; | |
public push(value: number): void { | |
const node = new Nodo(value); | |
node.next = this.head; | |
this.head = node; // head = 2 -> 1 -> null | |
this.length += 1; | |
} | |
public pop(): number { | |
if (this.isEmpty()) { | |
return null; | |
} | |
const value = this.head.value; | |
this.head = this.head.next; // head = 1 -> null | |
this.length -= 1; | |
return value; | |
} | |
public peek(): number { | |
if (this.isEmpty()) { | |
return null; | |
} | |
return this.head.value; | |
} | |
public size(): number { | |
return this.length; | |
} | |
public isEmpty(): boolean { | |
return this.head == null; | |
} | |
} | |
const s = new Stack(); | |
console.log('IS EMPTY:', s.isEmpty()); | |
s.push(1); | |
s.push(2); | |
s.push(3); | |
console.log('IS EMPTY:', s.isEmpty()); | |
console.log('PEEK:', s.peek()); // 3 | |
console.log('LEN:', s.size()); // 3 | |
s.pop(); | |
s.pop(); | |
s.pop(); | |
console.log('IS EMPTY:', s.isEmpty()); | |
console.log('LEN:', s.size()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment