Question
输入一个链表,输出该链表中倒数第k个结点。
关键词:链表 顺序
Solution
暴力遍历
顺序遍历所有结点得到链表总长度,再顺次得到倒数第k个节点。另外可以利用栈,先压入所有结点,然后推出第k个结点。
时间复杂度:O(2N)
空间复杂度:O(1)
- Python
class Solution:
def FindKthToTail(self, head, k):
if not head or k==0:
return None
count = 0
chead = head
while head:
head = head.next
count += 1
if k>count:
return None
for i in range(count-k):
chead = chead.next
return chead
- C++
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
if (!pListHead || k==0)
return NULL;
int count = 0;
ListNode* save = pListHead;
while(pListHead){
count += 1;
pListHead = pListHead->next;
}
if(k>count)
return NULL;
for(int i = 0; i < count - k; i++)
save = save->next;
return save;
}
};
先跑与后跑
A结点先跑k-1步,B结点再出发,由于AB距离为k-1,当A跑到尾端时,B正好处于倒数第k个结点上。
时间复杂度:O(N)
空间复杂度:O(1)
- Python
class Solution:
def FindKthToTail(self, head, k):
if not head or k==0:
return None
tail = head
for i in range(k-1):
if tail.next:
tail = tail.next
else:
return None
while tail.next:
head, tail = head.next, tail.next
return head
- C++
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
if (!pListHead || k==0)
return NULL;
ListNode* a = pListHead;
ListNode* b = pListHead;
for(int i = 0; i < k-1; i++){
if(a->next)
a = a->next;
else
return NULL;
}
while(a->next){
a = a->next;
b = b->next;
}
return b;
}
};