Python:如何找出单链表中的倒数第K个元素

本文深入讲解了链表的基本操作,包括链表的构建、打印以及查找倒数第K个节点的算法实现。通过具体代码示例,展示了如何使用Python进行链表节点的创建、链接和遍历,以及如何定位链表的特定位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class LNode:
    def __init__(self):
        self.data = None
        self.next = None

def ConstructList():
    i = 1
    head = LNode()
    cur = head
    while i<8 :
        tmp = LNode()
        tmp.data = i
        cur.next = tmp
        cur = tmp
        i += 1
    return head

def PrintList(head):
    if head is None or head.next is None:
        print('Empty!')
        return
    cur = head.next
    while cur is not None:
        print(cur.data,end=' ')
        cur = cur.next

def FindLastK(head, k):
    if head == None or head.next == None :
        return head
    slow = LNode()
    fast = LNode()
    fast = head.next
    slow = head.next
    i = 0
    while i<k and fast != None:
        fast = fast.next
        i += 1
    if i<k :
        return None
    while fast != None:
        slow = slow.next
        fast = fast.next
    return slow

if __name__ == '__main__':
    head = ConstructList()
    print('链表:',end='')
    PrintList(head)
    result = FindLastK(head, 3)
    if result is not None:
        print('\n链表的倒数第3个元素为:'+str(result.data))

运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值