
一、前言
本系列文章为《剑指Offer》刷题笔记。
刷题平台:牛客网
书籍下载:共享资源
二、题目
输入一个链表,输出该链表中倒数第k个结点。
1、思路
我们可以定义两个指针。第一个指针从链表的头指针开始遍历向前走k-1,第二个指针保持不动;从第k步开始,第二个指针也开始从链表的头指针开始遍历。由于两个指针的距离保持在k-1,当第一个(走在前面的)指针到达链表的尾结点时,第二个指针(走在后面的)指针正好是倒数第k个结点。
效果示意图,以链表总共6个结点,求倒数第3个结点为例:
除此之外,要注意代码的鲁棒性。需要判断传入参数合法性问题。
2、代码
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 == 0){
return NULL;
}
ListNode *pAhead = pListHead;
ListNode *pBehind = pListHead;
for(unsigned int i = 0; i < k - 1; i++){
if(pAhead->next != NULL){
pAhead = pAhead->next;
}
else{
return NULL;
}
}
while(pAhead->next != NULL){
pAhead = pAhead->next;
pBehind = pBehind->next;
}
return pBehind;
}
};
Python2.7:
方法与C++一致:
# -*- 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 == None or k == 0:
return None
phead = head
pbehind = head
for i in range(k-1):
if phead.next == None:
return None
else:
phead = phead.next
while phead.next != None:
phead = phead.next
pbehind = pbehind.next
return pbehind
用列表,开辟新空间了,不太好。
# -*- 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
l = []
while head:
l.append(head)
head = head.next
if len(l) < k or k < 1:
return None
return l[-k]
来源:
https://cuijiahua.com/blog/2017/12/basis_14.html

