问题描述
输入一个链表,输出该链表中倒数第k个结点。
解题思路
两个指针都指向头结点,第一个指针先移动k-1个结点,之后两指针同时移动,当第一个指针到链表尾的时候,第二个指针刚好指向倒数第k个结点。
c++代码
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 == NULL || k == 0) return NULL; 13 ListNode *p1 = pListHead, *p2 = pListHead; 14 int cnt = 1; 15 while(cnt < k && p1!=NULL){ 16 p1 = p1->next; 17 cnt = cnt+1; 18 } 19 if(cnt < k || p1 == NULL) return NULL; 20 while(p1->next != NULL){ 21 p1 = p1->next; 22 p2 = p2->next; 23 } 24 return p2; 25 } 26 };
python代码
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 if head is None or k == 0: 11 return None 12 p1, p2 = head, head 13 cnt = 1 14 while cnt < k and p1: 15 p1 = p1.next 16 cnt = cnt + 1 17 if cnt < k or p1 is None: 18 return None 19 while p1.next: 20 p1 = p1.next; 21 p2 = p2.next; 22 return p2