知识点:链表
一、题目描述:
输入一个链表,输出该链表中倒数第k个结点。
二、解题思路:
1:利用双指针
以链表1->2->3->4->5->6,k=3为例:
C++实现:
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
ListNode *p = pListHead;
ListNode *q = pListHead;
int i = 0;
while(p!=NULL){//遍历链表,当i>=k,指针p和q同时走
if(i >= k)
{
q = q->next;
}
p = p->next;
i++;
}
return i<k? NULL: q;//当i<k的时候指针q指向的是头结点,所以返回NULL
}
};
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
p = head;
q = head;
index = 0;
while p!=None:
if index >= k:
q = q.next
p = p.next
index += 1
return None if index < k else q
2:两次遍历。第一次遍历获取链表长度n,第二次遍历链表获取第n-k+1个节点(索引从0开始),即倒数第k个节点。
C++实现:
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
/*
if(pListHead== NULL || k<0){
return NULL;
}
*/
//获取链表长度n
ListNode* p;
ListNode* q;
p = pListHead;
q = pListHead;
int n = 0;
while(p!=NULL){
n++;
p = p->next;
}
if(k>n){//需要判断是否越界
return NULL;
}
//n-k+1个节点
for(int i=0; i<n-k; i++){
q = q->next;
}
return q;
}
};
python实现:
class Solution:
def FindKthToTail(self, head, k):
# write code here
if head==None or k<=0:
return None
p = head
q = head
#获取链表长度n
n = 0
while p!=None:#C++中的NULL,在python中为None
n += 1
p = p.next#C++中->
if k>n:
return None
#获取第n-k+1个节点
'''
#while循环
cnt=0
while q!=None:
cnt += 1
if cnt==n-k+1:
return q
q=q.next
'''
#用for循环
for i in range(0,n-k):#range(0,n-k+1)错误,range(1,n-k+1)正确
q = q.next
return q