Python 找出单向链表中倒数第k个节点

实现一个算法,找出单向链表中倒数第k个节点

class Node():
    def __init__(self,val):
        self.val = val
        self.next = None
class LinkList:
    def __init__(self):
        self.head = Node(Node)
    def init(self,iter):
        p = self.head
        for i in iter:
            p.next = Node(i)
            p = p.next
    def find_re_k(self,k): #思路:先将p1指向head,然后走k步,把当前P1赋值给p2,p1再回到head,然后p1,p2同时走,当p2到最后时,p1所指的就是倒数第k个元素。.,
        p1 = self.head#p1指向head
        i =0
        while i< k-1:
            p1 = p1.next
            i += 1
        p2 = p1 #P1赋值给p2
        p1 = self.head  #p1再回到head
        while p2.next is not None:
            #p1,p2同时走
            p2 = p2.next
            p1 = p1.next
        return p1.val
    def __str__(self):
        l = []
        p = self.head.next
        while p is not None:
            l.append(p.val)
            p = p.next
        return str(l)
if __name__ == '__main__':
    l = LinkList()
    l1 = (1,2,3,4)
    l.init(l1)
    print(l)
    print(l.find_re_k(1))

你可能感兴趣的:(Python 找出单向链表中倒数第k个节点)