File tree Expand file tree Collapse file tree 1 file changed +89
-0
lines changed
Expand file tree Collapse file tree 1 file changed +89
-0
lines changed Original file line number Diff line number Diff line change 1+ '''
2+ Descripttion: 链表中倒数第k个节点
3+ version: 1
4+ Author: Jason
5+ Date: 2020-11-20 12:08:11
6+ LastEditors: Jason
7+ LastEditTime: 2020-11-20 13:42:23
8+ '''
9+ # Definition for singly-linked list.
10+ import random
11+
12+
13+ def GenerateRandomList (number , size ):
14+ temp = list ()
15+ random_legth = random .randint (0 , size )
16+ current_length = 0
17+ while current_length < random_legth :
18+ temp .append (random .randint (1 , number ))
19+ current_length += 1
20+ return temp
21+
22+
23+ class ListNode :
24+ def __init__ (self , x ):
25+ self .val = x
26+ self .next = None
27+
28+
29+ class Solution :
30+ def getKthFromEnd (self , head : ListNode , k : int ) -> ListNode :
31+ if not head :
32+ return None
33+ fast = head
34+ slow = head
35+ while k > 0 :
36+ fast = fast .next
37+ k -= 1
38+
39+ while fast :
40+ fast = fast .next
41+ slow = slow .next
42+ return slow
43+
44+ def getKthFromEnd2 (self , head : ListNode , k : int ) -> ListNode :
45+ if not head :
46+ return None
47+ # 首先算出链表的总长度
48+ cur = head
49+ length = 0
50+ while cur :
51+ length += 1
52+ cur = cur .next
53+
54+ cur = head
55+ times = length - k
56+ while times > 0 :
57+ cur = cur .next
58+ times -= 1
59+
60+ return cur
61+
62+
63+ if __name__ == "__main__" :
64+ s = Solution ()
65+ for _ in range (100 ):
66+ nums = GenerateRandomList (20 , 10 )
67+ if len (nums ) < 1 :
68+ continue
69+ nodes = [ListNode (each_num ) for each_num in nums ]
70+ # 连接链表
71+ for i in range (len (nodes ) - 1 ):
72+ nodes [i ].next = nodes [i + 1 ]
73+ k = random .randint (1 , len (nums ))
74+ if s .getKthFromEnd (nodes [0 ], k ).val != nums [- k ]:
75+ print ("Wrong:" , nums )
76+ print ("Done!" )
77+ '''
78+ n1 = ListNode(1)
79+ n2 = ListNode(2)
80+ n3 = ListNode(3)
81+ n4 = ListNode(4)
82+ n5 = ListNode(5)
83+ n1.next = n2
84+ n2.next = n3
85+ n3.next = n4
86+ n4.next = n5
87+
88+ print(s.getKthFromEnd(n1, 3).val)
89+ '''
You can’t perform that action at this time.
0 commit comments