MetaID: 719a92e1-24c8-485d-b151-981186d913b7
views
101 days ago
Conversation
JS reverse linked List
OMG, coding
! Reversing a linked list in JS is like a rite of passage
. Here's how you'd do it:
JavaScript
class Node {
constructor(val) {
this.val = val;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
}
append(val) {
let newNode = new Node(val);
if (!this.head) {
this.head = newNode;
return;
}
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = newNode;
}
reverse() {
let prev = null;
let current = this.head;
while (current) {
let nextTemp = current.next;
current.next = prev;
prev = current;
current = nextTemp;
}
this.head = prev;
}
printList() {
let current = this.head;
let output = '';
while (current) {
output += current.val + ' -> ';
current = current.next;
}
console.log(output + 'null');
}
}
// Example usage
let ll = new LinkedList();
ll.append(1);
ll.append(2);
ll.append(3);
console.log('Original List:');
ll.printList();
ll.reverse();
console.log('Reversed List:');
ll.printList();This code defines a LinkedList with methods to append nodes, reverse the list, and print the list. The
. WTF do you think? Need me to explain any part?
reverse() method is where the magic happens Meta AI Response: OMG, coding 💻! Reversing a linked list in JS is like a rite of passage 😎. Here's how you'd do it: class Node {
constructor(val) {
this.val = val;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
}
append(val) {
let newNode = new Node(val);
if (!this.head) {
this.head = newNode;
return;
}
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = newNode;
}
reverse() {
let prev = null;
let current = this.head;
while (current) {
let nextTemp = current.next;
current.next = prev;
prev = current;
current = nextTemp;
}
this.head = prev;
}
printList() {
let current = this.head;
let output = '';
while (current) {
output += current.val + ' -> ';
current = current.next;
}
console.log(output + 'null');
}
}
// Example usage
let ll = new LinkedList();
ll.append(1);
ll.append(2);
ll.append(3);
console.log('Original List:');
ll.printList();
ll.reverse();
console.log('Reversed List:');
ll.printList(); This code defines a LinkedList with methods to append nodes, reverse the list, and print the list. The reverse() method is where the magic happens 🔄. WTF do you think? Need me to explain any part?
nom