Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Node {
- constructor(value){
- this.value = value
- this.next = null
- }
- setNext(next){
- this.next = next
- }
- getNext(){
- return this.next
- }
- }
- class LinkedList {
- constructor(){
- this.length = 0
- this.head = null
- this.tail = null
- }
- push(value){
- const newNode = new Node(value)
- if(this.length === 0) {
- this.head = this.tail = newNode
- }
- else {
- this.tail.setNext(newNode)
- this.tail = newNode
- }
- this.length++
- }
- pop(){
- if(this.length === 0) { return null }
- else {
- const oldTail = this.tail
- this.tail = this._findByIndex(this.length-2)
- this.tail.setNext(null)
- this.length--
- if(this.length === 0) { this.head = null }
- return oldTail.value
- }
- }
- get(index){
- return this._findByIndex(index).value
- }
- delete(index){
- let deletedNode
- if(index === 0) {
- deletedNode = this.head
- this.head = this.head.getNext()
- }
- else {
- const preNode = this._findByIndex(index-1)
- deletedNode = preNode.getNext()
- preNode.setNext(deletedNode.getNext())
- }
- this.length--
- return deletedNode.value
- }
- _findByIndex(index){
- let currentNode = this.head,
- counter = 0,
- max = this.length
- while (counter < max) {
- if(counter === index){
- return currentNode
- }
- currentNode = currentNode.getNext()
- counter++
- }
- }
- _findByNext(findNextNode){
- let currentNode = this.head
- while (currentNode.getNext() !== null) {
- currentNode = currentNode.getNext()
- if(currentNode.getNext() === findNextNode){
- return currentNode
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment