描述:输入一个单向链表,输出该链表中倒数第k个结点,链表的倒数第1个结点为链表的尾指针。
链表结点定义如下:struct ListNode {int m_nKey; ListNode* m_pNext;};
正常返回倒数第k个结点指针,异常返回空指针.
要求:(1)正序构建链表;(2)构建后要忘记链表长度。
数据范围:链表长度满足 1 \le n \le 1000 \1≤n≤1000 , k \le n \k≤n ,链表中数据满足 0 \le val \le 10000 \0≤val≤10000 ;本题有多组样例输入。
输入描述:
1 输入链表结点个数
2 输入链表的值
3 输入k的值
输出描述:输出一个整数
输入:
8
1 2 3 4 5 6 7 8
4
输出:5
class Node(object):
# node为新的数据类型,人为创建的,相当于key-int和next-下个节点指针的组合类型。
# 类似披着羊皮的狼,方便去找下一个羊,地有个next指针羊皮
def __init__(self,key=None,next=None):
self.key = key
self.next = next
class singleLinkList(object):
def __init__(self,node=None):
self.__head = node
def add_left(self,one):
# 每次将有next的node节点写入最前面,则最终为 87654321倒序
# 初始化的head指针,先让node新节点next指向head,再head重新指向node节点
# 则可通过head找到node,则链起来了node节点
# 每次新插入node,只是和head打交道,不需要跟尾部插入right方法要遍历到最后节点才行
node = Node(one)
node.next = self.__head
self.__head = node
# 从头节点的尾部写入数据,则可对for循环的每个值写入到后面依次加进来
def add_right(self,one):
node = Node(one)
# 要插入的node前提要判断下是否head为空,如为空,则node直接为head节点指向即可
if self.__head == None:
node.next = self.__head
self.__head = node
else:
# 如有其他node节点,则先从head开始遍历,遍历条件为next不为空
current = self.__head
while current.next != None:
current = current.next
# 遍历到最后,则next指向None时,则将current当前节点的next指向新的nod初始化变量地址
current.next = node
def printnode(self):
current = self.__head
# 每次current都是默认head开始,作为初始化
# 需要一个个遍历current节点对于的key值,node类似于元组key1和next2组成
# 链表中每个next都指向了下一个节点对应的地址,地址赋值给next
while current != None:
# print(current.key)
current = current.next
def findNode(self,num,loc):
# num为总的第一行输入的长度
# step为总长度减去倒序k个节点,则对应为总长度减去倒叙的loc个节点则为,顺序的节点步数到对应key的值
loc = loc
num = num
step = num - loc
current = self.__head
while step:
current = current.next
step -= 1
# print('while-loc:',current.key)
# while-loc: 2
# while-loc: 3
# while-loc: 4
# while-loc: 5
# 输入1个值,则不进入while判断,因为step=1-1=0直接输出current.key值则为结果
# while-loc: 4218
# while-loc: 9064
# while-loc: 4908
# while-loc: 1526
# while-loc: 6655
# while-loc: 921
print(current.key)
# 输入1个值,则不进入while判断,因为step=1-1=0直接输出current.key值则为结果
# 5
# 8108
# 921
while True:
try:
# 每次输入3行,则进入一个while true判断,因num及values及loc取了3行数据后则完成了一轮数据处理
# 8
# 1 2 3 4 5 6 7 8
# 4
# 1
# 8108
# 1
# 7
# 2542 4218 9064 4908 1526 6655 921
# 1
# singleLinkeList初始化时候设置了node=None默认,则可不执行node(-1)操作
# nod = Node(-1)
num = int(input().strip())
sl = singleLinkList()
values = list(map(int,input().strip().split(' ')))
for i in range(num):
# for循环每次写入key时候,需要在函数内进行Node(one)初始化操作,会将i封装成有next的i/key
sl.add_right(values[i])
sl.printnode()
loc = int(input().strip())
sl.findNode(num=num,loc=loc)
except:
break