思路:
设置2个指针,第一个指针先走k步,第二个指针开始走,这样在第一个指针走到末尾时,第二个指针刚好指向倒数第K个节点
class listnode(object):
def __init__(self, x):
self.val=x
self.next=None
def findkth(head, k):
if not head or not k:
return
p1,p2 = head, head
for i in range(k-1):
if p1.next == None: #这里要小心链表长度小于k的情况
return None
p1 = p1.next
while p1.next != None: #p1已经先走完,现在和P2开始一起走
p1 =p1.next
p2 =p2.next
return p2
测试:
node1 = listnode(1)
node2 = listnode(2)
node3 = listnode(3)
node4 = listnode(4)
node1.next = node2
node2.next = node3
node3.next = node4
new = findkth(node1, 2)
new.val
3
本文地址:https://blog.csdn.net/kasiko/article/details/107304617
如对本文有疑问, 点击进行留言回复!!
VSCode出现ERROR: Could not find a version that satisfies the requirement cv2 (from versions: none)错误
从零开始的PYTHON3摸鱼(二)windows如何运行python,编辑器选择
网友评论