其实想法也很简单,用我们常用的列表来进行中间操作,就是用一个stack保存原本链表的所有值,然后再新建两个链表 res和res2 分别用来输出结果 和 迭代 ListNode的next节点
class Solution:
def FindKthToTail(self , pHead , k ):
# write code here
if not pHead or k ==0:
return None
stack = []
res = ListNode(0)
res2 = res
while pHead:
stack.append(pHead.val)
pHead = pHead.next
if len(stack) < k:
return None
for i in stack[-k:]:
res2.next = ListNode(i)
res2 = res2.next
return res.next
def FindKthToTail(self , pHead , k ):
# write code here
if not pHead or k ==0:
return None
stack = []
res = ListNode(0)
res2 = res
while pHead:
stack.append(pHead.val)
pHead = pHead.next
if len(stack) < k:
return None
for i in stack[-k:]:
res2.next = ListNode(i)
res2 = res2.next
return res.next