MetaID: 493c9f06-6852-4cdf-ae56-74ed3e6be61b
views
101 days ago
Conversation
reverse linked list in js
JavaScript
function reverseLinkedList(head) {
let prev = null;
let current = head;
let next = null;
while (current !== null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
return prev;
}
// Node class definition
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
// Example usage
let head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head = reverseLinkedList(head);
// Print reversed list
while (head !== null) {
console.log(head.data);
head = head.next;
}Meta AI Response: function reverseLinkedList(head) {
let prev = null;
let current = head;
let next = null;
while (current !== null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
return prev;
}
// Node class definition
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
// Example usage
let head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head = reverseLinkedList(head);
// Print reversed list
while (head !== null) {
console.log(head.data);
head = head.next;
}