算法-找出链表的倒数第K个节点
1.题目描述
输入一个链表,输出该链表中倒数第k个节点。为了符合大多数人的习惯,本题从1开始计数,即链表的尾节点是倒数第1个节点
示例 1:
输入:head = [1,2,3,4,5], n = 2
输出:4
难度: 简单
2.解法
方法一: 常规解法
思路:
1.先遍历统计链表长度,记为N
2.再次遍历链表,N-K即为倒数第K个节点
class Node():
def __init__(self, value, next=None):
self.value = value
self.next = next
class LinkNode():
def __init__(self):
self.head = None
self.len = 0
def appendNode(self, value):
newNode = Node(value)
if not self.head:
self.head = newNode
self.len += 1
else:
tmp = self.head
while tmp.next:
tmp = tmp.next
tmp.next = newNode
self.len += 1
def print_link(self):
if not self.head:
return
temp = self.head
while temp.next:
print(temp.data)
temp = temp.next
class Solution():
# 暴力解法
def getKthFromEnd(self, head, k):
count = 0
current_node, new_node = head, head
while current_node:
current_node = current_node.next
count += 1
i = 0
while i <= count - k:
new_node = new_node.next
i += 1
return new_node
if __name__ == '__main__':
linkNode = LinkNode()
for i in range(8):
linkNode.appendNode(i)
solution = Solution()
res=solution.getKthFromEnd(linkNode.head, 2)
print(res.value)
时间复杂度O(N) 空间复杂度O(1)
方法二:双指针
思路:
1.初始化双指针former和latter,指针former先于latter往前走K步
2.former和latter同时往前移动,直到former到达链表末尾,此时latter即为倒数第K个节点
class Solution():
def getKthFormEndNew(self, head, k):
former, latter = head, head
for _ in range(k):
former = former.next
while former:
former, latter = former.next, latter.next
return latter
if __name__ == '__main__':
linkNode = LinkNode()
for i in range(8):
linkNode.appendNode(i)
solution = Solution()
res=solution.getKthFormEndNew(linkNode.head, 2)
print(res.value)
时间复杂度O(N) 空间复杂度O(1)