时间限制:1秒 空间限制:32768K
本题知识点: 链表
题目描述
输入一个链表,输出该链表中倒数第k个结点。
思路1:
遍历两次数组,第一次先统计出来个数n,第二次再求出n-k+1,将求倒数第k节点的问题转化为正数第n-k+1的问题
C++
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int m) {
if(pListHead==NULL||m<1)return NULL;
int count = 0;
ListNode* pFind = pListHead;
while(pFind != NULL){//记录链表总节点数,方便后续倒数转正数
count+=1;
pFind = pFind->next;
}
int pos = count - m + 1;//将倒数位置转化成正数位置
if( pos < 1)return NULL;
int flg = 1;
pFind = pListHead;
while(pFind != NULL && flg != pos){
pFind = pFind->next;
flg++;
}
return pFind;
}
};
Python
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def FindKthToTail(self, head, k):
if k<=0 or head==None:
return None
count=0
pFind=head
while pFind != None:
count=count+1
pFind=pFind.next
if count<k:
return None
pos=count-k+1
flg=0
pFind=head
while pFind!=None:
flg=flg+1
if flg==pos:
return pFind
pFind=pFind.next