educative.io

A Cleaner solution

class Node {
  constructor(value, next = null) {
this.value = value;
this.next = next;
  }

  get_list() {
result = "";
temp = this;
while (temp !== null) {
  result += temp.value + " ";
  temp = temp.next;
}
return result;
  }
};

const reverse_sub_list = function (head, p, q) {
  let curr = head
  let i = 1

  // go to the p-1 node
  while (i < p - 1) {
curr = curr.next
i += 1
  }

  // save ref to list before reversed section
  // and last node of the reversed section
  const beforeRev = curr
  const lastRevNode = beforeRev.next

  // setup reversing
  let prev = curr.next
  curr = curr.next.next
  i += 2

  // reverse nodes
  while (i <= q) {
const next = curr.next

curr.next = prev
prev = curr
curr = next
i += 1
  }

  // link all sections
  beforeRev.next = prev
  lastRevNode.next = curr

  return head;
};


head = new Node(1)
head.next = new Node(2)
head.next.next = new Node(3)
head.next.next.next = new Node(4)
head.next.next.next.next = new Node(5)

console.log(`Nodes of original LinkedList are: ${head.get_list()}`)
console.log(`Nodes of reversed LinkedList are: ${reverse_sub_list(head, 2, 4).get_list()}`)

Course: Grokking the Coding Interview: Patterns for Coding Questions - Learn Interactively
Lesson: Reverse a Sub-list (medium) - Grokking the Coding Interview: Patterns for Coding Questions

Hello @Nicolas_F!

Thank you for this cleaner solution really appreciate that.
Thanks again and good luck.

1 Like