题目描述
输入一个链表,输出该链表中倒数第k个结点。
思路
设置两个指针 fast 、slow,fast先走k-1步,然后再一起走;
先走的k-1步中,如果遇到fast=nullptr,说明链表长度小于k-1,就没有倒数第k项,那就直接返回空指针;
当fast走到最后一个结点,slow恰好在倒数第k个结点。
1 /* 2 struct ListNode { 3 int val; 4 struct ListNode *next; 5 ListNode(int x) : 6 val(x), next(NULL) { 7 } 8 };*/ 9 class Solution { 10 public: 11 ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) { 12 if(!pListHead || k<=0) return nullptr; 13 ListNode* fast = pListHead; 14 ListNode* slow = pListHead; 15 for(int i=0;i<k-1;i++){ 16 fast = fast->next; 17 if(!fast) return nullptr; 18 } 19 while(fast->next){ 20 fast = fast->next; 21 slow = slow->next; 22 } 23 return slow; 24 } 25 };
pyhton
1 # -*- coding:utf-8 -*- 2 # class ListNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.next = None 6 7 class Solution: 8 def FindKthToTail(self, head, k): 9 # write code here 10 res = [] 11 while head: 12 res.append(head) 13 head = head.next 14 if k<1 or k>len(res): 15 return 16 return res[-k]