Thursday, September 5, 2013

2.2 --- find the kth to the last element of a singlely linked list

Q:
Implement an algorithm to find the kth to last element of a singly linked list.

A:

假设只需要得到答案从前数是第几个,( 可以),利用一个变量来记下,递归的次数,nthToLast(curNode.next, k)  ,以此来返回从正向数,应该输出的index数。(不能得到data)。

Method 1: use two iterations, first to calculate the size of list.
               Then run through size - k  of the elements.

Method 2:  use two pointers, with their distance as k.


 public static Node twoRunKthtoLast(LinkList list, int k) {
  int listSize = 0;
  Node pointer = list.head;
  while (pointer != null) {
   listSize++;
   pointer = pointer.next;
  }
  if (k > listSize) {
   System.err.println("no enough node in list");
   return null;
  } else {
   int frontIndex = listSize - k;
   pointer = list.head;
   for (int i = 0; i < frontIndex; i++) {
    pointer = pointer.next;
   }
   return pointer;
  }
 }

 public static Node twoPointerKthtoLast(LinkList list, int k) {
  Node preRunner, behindRunner;
  preRunner = list.head;
  for (int i = 0; i < k; i++) {
   if (preRunner == null) {
    System.err.println("no enough node in list");
    return null;
   } else {
    preRunner = preRunner.next;
   }
  }
  // Now all preRunner point to the k+1 th element,
  behindRunner = list.head;
  while (preRunner != null) {
   preRunner = preRunner.next;
   behindRunner = behindRunner.next;
  }

  return behindRunner;
 }




Mistakes:
1:LinkList.head 所指向的,是一个node, 因此不能计数
2:  永远记住, 返回的对象,可能是null的。 不能随便用它来干活儿。  LOL







No comments:

Post a Comment