#思路:遍历整个链表,把链表中的元素放在列表中,索引第n-k个元素
class Node():
def __init__(self,data):
self.data = data
self.next = None
class singleList():
def __init__(self):
self._head = None
# 尾插法建立列表
def append(self,data):
if self._head == None:
s = Node(data)
self._head = s
else:
p =self._head
while p.next !=None:
p=p.next
s= Node(data)
p.next = s
def countlength(self):
p = self._head
count = 0
while p!= None:
count += 1
p= p.next
return count
def findk(self,k,count):
res = []
if k > count:
return -1
else:
p = self._head
while p!=None:
# print(p.data)
res.append(p.data)
p = p.next
return res[count-k]
slist = singleList()
data = int(input("请输入链表list1中的值,输入-1结束:"))
while data!=-1:
slist.append(data)
data = int(input("请输入链表list1中的值,输入-1结束:"))
count = slist.countlength()
print(slist.findk(2, count))