编程题目：输入一个链表，输出该链表中倒数第k个节点

1.在链表的初始化数据中加入 num 数据， 每添加一个节点，num加1，每删除一个节点，num减1

2.使用两个指针 i 和 j， i和j初始化都指向第一个节点。

``` 1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3
4 class Node(object):
5         def __init__(self, elem, next_=None):
6                 self.elem = elem
7                 self.next = next_
8
9 class Simple_List(object):
10         def __init__(self):
12                 self.num = 0
13
14         def is_empty(self):
16
17         def prepend(self, elem):
19                 self.num += 1
20
21         def prepop(self):
22                 if self.is_empty():
23                         raise ValueError("List is Empty")
26                 self.num -= 1
27                 return e
28
29         def bianli(self):
31                 li = []
32                 while p:
33                         li.append(p.elem)
34                         p = p.next
35                 return li
36
37         def find_the_key(self, key):
38                 n = self.num - key
40                 while n:
41                         p = p.next
42                         n -= 1
43                 return p.elem
44
45         def find_the_key1(self,key):
47                 while key-1:
48                         j = j.next
49                         key -= 1
50                 while j.next:
51                         i = i.next
52                         j = j.next
53                 return i.elem
54
55 if __name__ == "__main__":
56         sl = Simple_List()
57         for i in [1,4,8,2,4,8,5]:
58                 sl.prepend(i)
59         print("链表:",sl.bianli())
60         key = int(input("查看该链表倒数第k个值:"))
61         print("倒数第k个值:",sl.find_the_key(key))
62         print("倒数第k个值:",sl.find_the_key1(key))```

```        def find_the_key(self, key):
if key < 1 or key > self.num:
raise ValueError("num must in 0<key<={}".format(self.num))
n = self.num - key
while n:
p = p.next
n -= 1
return p.elem

def find_the_key1(self,key):
if key < 1:
raise ValueError("num is unabled,please repeat input")
while key-1:
j = j.next
key -= 1
if j is None:
raise ValueError("num is unabled,please repeat input")
while j.next:
i = i.next
j = j.next
return i.elem```

原文作者：小黄人python
原文地址: https://www.cnblogs.com/xautxuqiang/p/6431730.html
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。