Last active
May 12, 2019 21:30
-
-
Save adrianosferreira/92880d7adac0ae4cbc92218ae2ef8f77 to your computer and use it in GitHub Desktop.
This file contains 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
function LinkedList() { | |
this.head = null; | |
this.tail = null; | |
} | |
function Node( prev, next, value ) { | |
this.prev = prev; | |
this.next = next; | |
this.value = value; | |
} | |
LinkedList.prototype.addToHead = function ( value ) { | |
var newNode = new Node( null, null, value ); | |
if ( this.head ) { | |
newNode.next = this.head | |
this.head.prev = newNode; | |
this.head = newNode; | |
} else { | |
this.head = newNode; | |
this.tail = newNode; | |
} | |
} | |
LinkedList.prototype.addToTail = function ( value ) { | |
var newNode = new Node( null, null, value ); | |
if ( this.tail ) { | |
newNode.prev = this.tail | |
this.tail.next = newNode; | |
this.tail = newNode; | |
} else { | |
this.head = newNode; | |
this.tail = newNode; | |
} | |
} | |
LinkedList.prototype.printAllNodes = function() { | |
currentNode = this.head; | |
while ( currentNode ) { | |
console.log( currentNode.value ); | |
currentNode = currentNode.next; | |
} | |
} | |
var arr = [1, 2, 2, 3, 1, 4, 5, 5, 5, 5, 7, 2, 2]; | |
function getResult( arr ) { | |
var ll = new LinkedList(); | |
arr.forEach( function(el){ | |
ll.addToTail( el ); | |
}); | |
var result = []; | |
var currentNode = ll.head; | |
var currentTotalValue = 1; | |
while( currentNode ) { | |
if ( currentNode.prev && currentNode.value === currentNode.prev.value ) { | |
currentTotalValue ++; | |
} else { | |
var item = currentNode.prev ? currentNode.prev.value : currentNode.value; | |
result.push( currentTotalValue > 1 ? item + ':' + currentTotalValue : item ); | |
currentTotalValue = 1; | |
} | |
currentNode = currentNode.next; | |
} | |
return result; | |
} | |
getResult(arr); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment