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

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

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

构造链表

  • 定义一个链表结构
  • 尾部添加链表
  • for循环链接,题目要求是倒数第k个,那我们正向for循环,取 链表长度 - k 的那个节点值,就是我们要的答案
  • 题目要求需要多次输入,所以要用while去保证可以多次输入样例
class ListNode:
    def __init__(self, val: int):
        self.val = val
        self.next = None


def append_link(head: ListNode, val: int):
    cur = head
    while cur.next is not None:
        cur = cur.next

    cur.next = ListNode(val)

    return head


def get_nth_from_the_end_in_link(head: ListNode, nth: int):
    link_length = 0
    cur = head
    while cur is not None:
        cur = cur.next
        link_length += 1

    count = link_length - nth
    res = head
    while count > 0 and res:
        count -= 1
        res = res.next
    
    if res:
        print(res.val)


while True:
    try:
        scan = int(input())
        numbers = list(map(int, input().split()))
        k = int(input())
        head = ListNode(numbers[0])
        for n in numbers[1:]:
            append_link(head, n)

        get_nth_from_the_end_in_link(head, k)
    except:
        break

全部评论

相关推荐

11-08 17:36
诺瓦科技_HR
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务