Python3链表 | #输出单向链表中倒数第k个结点#

输出单向链表中倒数第k个结点

https://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d

Python3,单向链表双指针做法,遵循题目“遗忘长度”要求。
class Node(object):
    def __init__(self, val):
        self.val = val
        self.next = None

class LinkList(object):
    def __init__(self, node=None):
        self.__head = node

    def isEmpty(self):
        return self.__head==None

    def append(self, item):
        node = Node(item)
        if self.isEmpty():
            self.__head = node
        else:
            cur = self.__head
            while cur.next != None:
                cur = cur.next
            cur.next = node

    def pop(self):
        if self.isEmpty() or self.__head.next == None:
            return None
        else:
            cur_left, cur_right = self.__head, self.__head.next
            while cur_right.next != None:
                cur_left, cur_right = cur_right, cur_right.next
            cur_left.next = None
            val =  cur_right.val
            del cur_right
            return val
    
    def getlast(self):
        cur = self.__head
        while cur.next != None:
            cur = cur.next
        return cur.val

while True:
    try:
        count = int(input())
        num_list = list(map(int, input().split()))
        k = int(input())
        ll = LinkList()
        for num in num_list:
            ll.append(num)

        for i in range(k-1):
            ll.pop()

        print(ll.getlast())
    except EOFError:
        break


全部评论

相关推荐

05-07 17:58
门头沟学院 Java
wuwuwuoow:1.简历字体有些怪怪的,用啥写的? 2.Redis 一主二从为什么能解决双写一致性? 3.乐观锁指的是 SQL 层面的库存判断?比如 stock > 0。个人认为这种不算乐观锁,更像是乐观锁的思想,写 SQL 避免不了悲观锁的 4.奖项证书如果不是 ACM,说实话没什么必要写 5.逻辑过期时间为什么能解决缓存击穿问题?逻辑过期指的是什么 其实也没什么多大要改的。海投吧
点赞 评论 收藏
分享
评论
1
2
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务