offer15

# coding=utf-8
'''求鏈表的倒數第k個節點
    思路:兩個指針保持k-1的距離'''
class Listnode: def __init__(self,x): self.val=x self.next=Noneclass Solution: def findk(self,head,k): if head==None or k<=0: return None phead=head pbehind=None for i in range(k-1): if phead.next!=None: phead=phead.next else: return None pbehind=head while phead.next!=None: phead=phead.next pbehind=pbehind.next return pbehindif __name__ == '__main__': node1=Listnode(1) node2=Listnode(2) node3=Listnode(3) node1.next=node2 node2.next=node3 s=Solution() print(s.findk(node1,2).val)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章