题目描述
输入一个链表,输出该链表中倒数第k个结点。
python实现:
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 法1:求链表长度L,倒数第k个节点,即整数第L+1-k个节点,然后正向遍历,再删除,但是此方法会遍历2遍
# 法2:先让p1走k步,然后p2从头,(p1与p2之间相隔k步)与p1同时向后走,p1走完链表
# p2恰好指着倒数第k个节点。注意位置的指向细节
# 例如:1->2->3->4->5->null
def FindKthToTail(self , pHead , k ):
# write code here
if pHead is None:
return None
if k<=0:
return None
p = pHead
i = 1
while i<=k:
if p:
p = p.next
else:
return None
i += 1
q = pHead
while p:
q = q.next
p = p.next
return q
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* p1=pListHead, *p2=NULL;
for(int i=1;i<k;i++){
if(p1)
p1=p1->next;
else
return NULL;
}
while(p1){
if(p2==NULL)
p2=pListHead;
else
p2=p2->next;
p1=p1->next;
}
return p2;
}
};