Skip to content

Instantly share code, notes, and snippets.

@lewdev
Created March 8, 2022 04:51
Show Gist options
  • Select an option

  • Save lewdev/4c36430cfa76e8a16598457ff25ae198 to your computer and use it in GitHub Desktop.

Select an option

Save lewdev/4c36430cfa76e8a16598457ff25ae198 to your computer and use it in GitHub Desktop.
Reverse a linked list in JavaScript and HTML.
<pre id=o></pre>
<script>
class LinkedList {
constructor(value, next) {
this.value = value;
this.next = next;
}
}
const reverseList = head => {
let curr = head;
let temp = null;
let prev = null;
while (true) {
temp = curr.next;
curr.next = prev;
prev = curr;
if (!temp) break;
curr = temp;
}
return curr;
};
const genLinkedList = arr => {
let newNode;
let head;
let node;
for (let i = 0; i < arr.length; i++) {
newNode = new LinkedList(arr[i]);
if (!head) {
head = newNode;
node = head;
}
else {
node.next = newNode;
node = node.next;
}
}
return head;
};
const linkedListToArr = head => {
let output = [];
let node = head;
while (node) {
const { value, next } = node;
output.push(value);
node = next;
}
return output;
};
const linkedList = genLinkedList([1,2,3,4,5,6]);
const reversed = reverseList(linkedList);
o.innerHTML = linkedListToArr(reversed).join("\n");
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment