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