解法:
- 定义两个指针,fast,slow指向链表的头结点。
- fast指针先走k步,走的时候要注意判断一下链表的长度是否大于等于k。如果链表的长度也等于k的话,快指针走k步正好会走到空。如果在走第k步之前链表就指向空的话,说明链表长度小于k,直接返回空。
- 然后fast指针和slow指针一起走。当fast指针指向空的时候,slow指针指向的就是倒数第k个节点。
例:k=2
fast先走两步
fast指向空的时候,slow指的就是倒数第二个结点了
c++
class Solution { public: ListNode* FindKthToTail(ListNode* pHead, int k) { ListNode* fast = pHead; ListNode* slow = pHead; for(int i = 0 ; i < k ; i++) { if(fast == NULL){return NULL;} fast = fast->next; } while(fast!=NULL) { fast = fast->next; slow = slow->next; } return slow; } };
java
public class Solution { public ListNode FindKthToTail (ListNode pHead, int k) { ListNode fast = pHead; ListNode slow = pHead; for(int i = 0 ; i < k ; i++) { if(fast == null){return null;} fast = fast.next; } while(fast!=null) { fast = fast.next; slow = slow.next; } return slow; } }
python
class Solution: def FindKthToTail(self , pHead , k ): fast = pHead; slow = pHead; for i in range(0,k): if fast == None: return None fast = fast.next; while fast!=None: fast = fast.next; slow = slow.next; return slow;