Skip to content

Latest commit

 

History

History
59 lines (46 loc) · 1.07 KB

File metadata and controls

59 lines (46 loc) · 1.07 KB

Implementation: linked-list-kth

Whiteboard Process

White-Borad

White Board Link

Approach & Efficiency

Solution

Node Class Code :

"use strict";
class Node {
  constructor(value) {
    this.value = value;
    this.next = null;
  }
}
module.exports = Node;

LinkedList Class Code :

"use strict";
const Node = require("./Node.js");
class LinkedList {
  constructor() {
    this.head = null;
  }
  kthFromEnd(k) {
    if (k < 0) {
      return "Exception";
    }

    let first = this.head;
    let last = this.head;

    for (let i = 0; i < k; i++) {
      if (last === null) {
        return "Exception";
      }
      last = last.next;
    }

    while (last !== null && last.next !== null) {
      first = first.next;
      last = last.next;
    }

    return first !== null ? first.data : null;
  }
}
module.exports = LinkedList;