【剑指offer】链表中倒数第K个结点(python)
我的思路是先遍历链表得到链表长度length,同时复制一份链表(不需要复制链表,只需要tmp=pHead,指向一块内存就行),因为遍历后指针指向链表末尾(pHead指针指向末尾,tmp还在开头),然后数tmp链表到第length-k个结点。
链表为空的判定条件和返回值
if pHead is None: return None
实现代码
# class ListNode: # def __init__(self, x): # self.val = x # self.next = None # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param pHead ListNode类 # @param k int整型 # @return ListNode类 # class Solution: ''' def Clone(self, pHead): if not pHead: return None cloneHead = ListNode(pHead.val) cloneHead.next = self.Clone(pHead.next) return cloneHead ''' def FindKthToTail(self , pHead , k ): # write code here count = 0 if pHead is None: return None # tmp = self.Clone(pHead) tmp = pHead while pHead: count+=1 pHead = pHead.next if k > count: return None else: for i in range(count - k + 1): if i == count - k: return tmp else: tmp = tmp.next
太蠢了,这个更简单一些,遍历的时候把结点复制到数组里,直接返回数组倒数第k个点。
# class ListNode: # def __init__(self, x): # self.val = x # self.next = None # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param pHead ListNode类 # @param k int整型 # @return ListNode类 # class Solution: def FindKthToTail(self , pHead , k ): # write code here result=[] if pHead is None: return None while pHead: result.append(pHead) pHead=pHead.next if k<1 or k>len(result): return None else: return result[-k]