MetaID: 47919be3-0dbc-4cc0-a5e0-f75bd856dcee
views
101 days ago
Conversation
js reverse linked list
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 next = current.next;
current.next = prev;
prev = current;
current = next;
}
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 class with methods to append nodes, reverse the list, and print the list. The
Do you want me to explain any part of this code or help with a variation of this problem?
reverse method uses a standard three-pointer approach to reverse the links between nodes. Meta AI Response: 😎 Here's how you can reverse a linked list in 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 next = current.next;
current.next = prev;
prev = current;
current = next;
}
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 class with methods to append nodes, reverse the list, and print the list. The reverse method uses a standard three-pointer approach to reverse the links between nodes. 💡 Do you want me to explain any part of this code or help with a variation of this problem?