diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ee96912..6ded7da 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -12,4 +12,5 @@ - ShivayeModi - Vishvesh Trivedi - Fahri Gunadi -- ekoyanu99 \ No newline at end of file +- ekoyanu99 +- Bagus \ No newline at end of file diff --git a/src/Javascript/ReverseLinkedList.js b/src/Javascript/ReverseLinkedList.js new file mode 100644 index 0000000..3d85731 --- /dev/null +++ b/src/Javascript/ReverseLinkedList.js @@ -0,0 +1,39 @@ +class ListNode { + constructor(val, next = null) { + + this.val = val; + this.next = next; + } +} + +const linkedList = [5, 4, 3, 2, 1].reduce((acc, val) => new ListNode(val, acc), null); + + +const printList = (head) => { + if(!head) { + return; + } + + console.log(head.val); + printList(head.next); +} + +// --------- solution ----------- + +var reverseList = function(head) { + let prev = null; + let current = head; + + while(current) { + let nextTemp = current.next; + current.next = prev; + prev = current; + current = nextTemp; + } + + return prev; +}; + +printList(linkedList); +console.log('after reverse') +printList(reverseList(linkedList)) \ No newline at end of file