JSFiddle - React, Tailwind, and code Playground
by Diana Lemen
JavaScript
function reverse(llist) {
const llistValues = []
class Node {
constructor(data, next = null, prev = null) {
this.data = data;
this.next = next;
this.prev = prev;
}
}
class LinkedList {
constructor () {
this.head = null;
this.tail = null;
}
push(data) {
let node = new Node(data);
if(!this.head) {
this.head = node;
this.tail = node;
return;
}
const prev = this.tail;
this.tail = node;
node.prev = prev;
prev.next = node;
}
}
llistValues.push(llist.data)
let next = llist.next
while(next) {
llistValues.push(next.data)
next = next.next
}
const reversed = llistValues.reverse();
const linkedList = new LinkedList();
for(let i = 0; i < reversed.length; i++) {
const tail = reversed[i + 1] || null;
linkedList.push(reversed[i]);
}
return linkedList.tail;
}
const list = { data: 1, next: { data: 2, next: { data: 3, next :{ data: 4, next: { data: 5, next: null} } } } }
console.log(reverse(list))