下面的函数尝试查找nth to 单链表的最后一个元素。
例如:
如果元素为8->10->5->7->2->1->5->4->10->10,则结果为7th to last node is 7。
有没有人能帮我讲讲这段代码是如何工作的,或者有没有更好更简单的方法?
LinkedListNode nthToLast(LinkedListNode head, int n) {
  if (head == null || n < 1) {
    return null;
  }
  LinkedListNode p1 = head;
  LinkedListNode p2 = head;
  for (int j = 0; j < n - 1; ++j) { // skip n-1 steps ahead
    if (p2 == null) {
      return null; // not found since list size < n
    }
    p2 = p2.next;
  }
  while (p2.next != null) {
    p1 = p1.next;
    p2 = p2.next;
  }
  return p1;
}发布于 2013-07-02 02:06:24
递归解决方案:
Node findKth (Node head, int count, int k) {
    if(head == null)
        return head;
    else {
        Node n =findKth(head.next,count,k);
        count++;
        if(count == k)
            return head;
        return n;
    }
}https://stackoverflow.com/questions/2598348
复制相似问题