時間限制: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