def FindKthToTail(self , pHead: ListNode, k: int) -> ListNode:
p1 = p2 = pHead
for i in range(k):
if p2 == None:
return None
p2 = p2.next
while p2:
p1,p2 = p1.next,p2.next
return p1
完整代码:
from myutils.MyList import *
class Solution:
def FindKthToTail(self , pHead: ListNode, k: int) -> ListNode:
p1 = p2 = pHead
for i in range(k):
if p2 == None:
return None
p2 = p2.next
while p2:
p1,p2 = p1.next,p2.next
return p1
pHead = Create([2])
k = 8
ans = Solution().FindKthToTail(pHead,k)
if ans:
ans.show()
else:
print('')
MyList.py
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def show(self):
p = self
while p is not None:
print(p.val, end=' ')
p = p.next
print()
# 只返回头节点
def Create(data):
# print('data',data)
if len(data) < 1:
return None
head = ListNode(data[0])
tail = head
for i in range(1, len(data)):
tail.next = ListNode(data[i])
tail = tail.next
return head
# 返回头节点和尾节点
def Create2(data):
# print('data',data)
if len(data) < 1:
return None, None
head = ListNode(data[0])
tail = head
for i in range(1, len(data)):
tail.next = ListNode(data[i])
tail = tail.next
return head, tail