题解 | #链表中倒数最后k个结点#
链表中倒数最后k个结点
https://www.nowcoder.com/practice/886370fe658f41b498d40fb34ae76ff9
public ListNode FindKthToTail (ListNode pHead, int k) { //参数校验 if(pHead == null) return null; //获取链表的长度 ListNode head = pHead; int length = getListNodeLength(pHead); int index = length - k + 1; if(index > 0){ int count = 1; while(index != count){ head = head.next; count ++ ; } return head; }else{ return null; } } private int getListNodeLength(ListNode pHead) { //记录链表的个数 int count = 1; while(pHead.next != null){ pHead = pHead.next; count ++ ; } return count; }
解题思路:
1、计算出链表的总长度length
2、倒数第k个节点就是正数length-k+1位置的节点,只要保证这个位置存在就行,找到该位置的节点将其输出