思路
经典双指针题目,leftPoint指向第一个节点,rightPoint指向第k个节点,左右指针相距k-1个身位,使用rightPoint去寻找尾节点,当寻找到尾节点时,那么leftPoint指向的节点便是倒数第k个节点了。
结果
运行时间:16ms
占用内存:10828KB
代码
public ListNode FindKthToTail (ListNode pHead, int k) { ListNode leftPoint = pHead; ListNode rightPoint = pHead; if (k <= 0) return null; for (int i = 0; i < k - 1; i++) { if (rightPoint == null || rightPoint.next == null){ return null; } rightPoint = rightPoint.next; } while (rightPoint.next != null){ rightPoint = rightPoint.next; leftPoint = leftPoint.next; } return leftPoint; }