codebuddies / DailyAlgorithms

Do a problem. Create (or find) your problem in the issues. Paste a link to your solution. See others' solutions of the same problem.
12 stars 1 forks source link

[Cracking the Code] Return kth to last element of a linked list #21

Open lpatmo opened 5 years ago

lpatmo commented 5 years ago

Return kth to last: implement an algorithm to find the kth to last element of a singly linked list.

Bonus: Implement an algorithm to find the kth element of a singly linked list (slightly easier)

lpatmo commented 5 years ago

"Pointer" (?) method:

function kth_to_last(llist, k) {
  //Quick Q: how do we find the length of the linked list? A: loop through it entirely
  //create copy of linked list
  //Start traversing through the first linked list. Don't start traversing through the second ll until you reach k in the first ll.
  // Then continue advancing both until the first pointer reaches the end. Return the node pointer in second ll is at when pointer in first ll reaches the end.
  let copy = llist;
  while (llist.next) {
    llist = llist.next
    k--;
    while (k <= 0) { // when llist.next reaches k, start traversing the second copy
      copy = copy.next
    }
  }
  return copy 
}

Bonus (get kth element):


function get_kth(llist, k) {
  while (k > 0 && llist.next) {
    k--;
    llist = llist.next
  }
  if (k > 0) { //Edge case: if k is > the length of the linked list
    return null;
  }
  return llist
}