Skip to content

Commit 286e41c

Browse files
双指针
某一个链表扫描退出循环后,只需cur.next指向未扫描完的那个链表的当前节点即可,无需再用while遍历
1 parent fee4f12 commit 286e41c

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed

newcoder/合并有序链表.py

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
'''
2+
Descripttion: 双指针+伪指针
3+
version: 1
4+
Author: Jason
5+
Date: 2020-12-08 17:45:52
6+
LastEditors: Jason
7+
LastEditTime: 2020-12-09 14:15:46
8+
'''
9+
10+
import random
11+
12+
13+
def GenerateRandomList(number, size):
14+
temp = [random.randint(0, number)]
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 mergeTwoLists(self, l1, l2):
31+
# write code here
32+
dummy = ListNode(float("inf"))
33+
cur = dummy
34+
p1, p2 = l1, l2
35+
while p1 and p2:
36+
if p1.val < p2.val:
37+
cur.next = p1
38+
p1 = p1.next
39+
else:
40+
cur.next = p2
41+
p2 = p2.next
42+
cur = cur.next
43+
# 有一个链表扫描完毕后,只需将目前的cur的next指向未扫描完的当前node即可,不用再while去扫描
44+
if p1:
45+
cur.next = p1
46+
else:
47+
cur.next = p2
48+
return dummy.next
49+
50+
51+
s = Solution()
52+
for _ in range(100):
53+
54+
nums1 = GenerateRandomList(20, 20)
55+
nums2 = GenerateRandomList(20, 20)
56+
nums1.sort()
57+
nums2.sort()
58+
nums_stand = sorted(nums1 + nums2)
59+
nodes1 = [ListNode(num) for num in nums1]
60+
nodes2 = [ListNode(num) for num in nums2]
61+
nodes_stand = [ListNode(num) for num in nums_stand]
62+
63+
for i in range(len(nums1) - 1):
64+
nodes1[i].next = nodes1[i + 1]
65+
66+
for i in range(len(nums2) - 1):
67+
nodes2[i].next = nodes2[i + 1]
68+
69+
for i in range(len(nums_stand) - 1):
70+
nodes_stand[i].next = nodes_stand[i + 1]
71+
72+
res = s.mergeTwoLists(nodes1[0], nodes2[0])
73+
74+
cur = nodes_stand[0]
75+
while cur:
76+
if cur.val != res.val:
77+
print("Wrong")
78+
print(nums1, nums2)
79+
break
80+
cur = cur.next
81+
res = res.next
82+
83+
if cur or res:
84+
print("Wrong")
85+
print("Done")

0 commit comments

Comments
 (0)