题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
https://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
'''
# 列表方法:
while True:
try:
n=int(input())
num=input().split()
k=int(input())
print(num[n-k]) # 倒数第0个,没有值,输出空值
#print(num[-k]) # k=0时,输出0,不对
except:
break
'''
# 创建一个节点类,包含数据元素和指向下一个数据元素的指针
class Node(object):
#创建单个节点类
def __init__(self,data,next=None):
self.data=data
self.next=next
# 创建一个单链表的类:包含一些功能(函数)
class SingleLinkedList(object):
def __init__(self):
self.__head=None #初始化头节点
def is_empty(self):
return self.__head is None # 判断链表是否为空 True/False
def length(self): #遍历链表,获取链表长度
cur=self.__head
cnt=0
while cur is not None: #当节点不为空时,返回cnt值
cnt += 1
cur = cur.next
return cnt
def append(self,item):
node=Node(item)
if self.is_empty():
self.__head=node
else:
cur=self.__head
while cur.next!=None:
cur=cur.next
cur.next=node
def pos_search(self,n,k):
cur=self.__head
cur_c=0
if k<=0:
print('0')
return False
else:
while cur!=None:
cur_c += 1
if cur_c==(n-k+1):
print(cur.data)
return True
else:
cur=cur.next
return False
if __name__=='__main__':
while True:
try:
n=int(input())
num=input()
k=int(input())
item=num.split(' ')
linklist=SingleLinkedList()
for i in range(n):
item_i=item[i]
linklist.append(item_i)
linklist.pos_search(n,k)
except:
break