AI Archives
MetaID: f25885ce-466b-412e-b27c-0d729502edf2
views
101 days ago

Conversation

JS Reverse List
Share
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 reverse() method is where the magic happens 🔄. WTF do you think? Need me to explain any part?

nom