问题描述
输入一个链表,输出该链表中倒数第k个结点。
解题思路
两个指针都指向头结点,第一个指针先移动k-1个结点,之后两指针同时移动,当第一个指针到链表尾的时候,第二个指针刚好指向倒数第k个结点。
c++代码
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
if(pListHead == NULL || k == ) return NULL;
ListNode *p1 = pListHead, *p2 = pListHead;
int cnt = ;
while(cnt < k && p1!=NULL){
p1 = p1->next;
cnt = cnt+;
}
if(cnt < k || p1 == NULL) return NULL;
while(p1->next != NULL){
p1 = p1->next;
p2 = p2->next;
}
return p2;
}
};
python代码
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None class Solution:
def FindKthToTail(self, head, k):
# write code here
if head is None or k == 0:
return None
p1, p2 = head, head
cnt = 1
while cnt < k and p1:
p1 = p1.next
cnt = cnt + 1
if cnt < k or p1 is None:
return None
while p1.next:
p1 = p1.next;
p2 = p2.next;
return p2