输入一个链表,输出该链表中倒数第k个结点。
第一种思路:
- 借助两个指针firstPointer,secondPointer
- 让第一个指针先跑k步 后
- 让第二个指针和第一个指针一直一起跑下去
- 直到第一个指针指向的节点的下一个节点为空
# -*- 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 k == 0 or head == None:
return None
firstPointer = head
secondPointer = head
for i in range(k):
if firstPointer == None:
return None
firstPointer = firstPointer.next
while firstPointer:
firstPointer = firstPointer.next
secondPointer = secondPointer.next
return secondPointer
思路二:
- 借助列表存放各个节点后输出列表的倒数第k个元素
# -*- 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 k == 0 or head == None:
return None
nodeList = []
nodePointer = head
while nodePointer:
nodeList.append(nodePointer)
nodePointer = nodePointer.next
if k >len(nodeList):
return None
else:
return nodeList[-k]