@author = yhr | 转载请标注来源!
题目描述
将两个有序的链表合并为一个新链表,
要求新的链表是通过 拼接 两个链表的节点来生成的,
且合并后新链表依然有序。
代码
没啥好介绍的啦~ 主要就是不要申请新节点咯~ 直接操作旧节点的next
直接上代码:
结点定义:
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
正式代码:
class Solution:
def merge(self, l1, l2):
head = ListNode(-65535) # 申请新链表的头节点 head指针指向头节点
rear = head # rear指针永远指向新链表的最后一个节点
p1 = l1 # p1指针负责遍历L1
p2 = l2 # p2指针负责遍历L2
while p1 is not None and p2 is not None:
if p1.val <= p2.val:
insert = p1
p1 = p1.next
else:
insert = p2
p2 = p2.next
insert.next = None # insert为当前目标插入节点
rear.next = insert
rear = insert
if p1 is not None:
rear.next = p1
elif p2 is not None:
rear.next = p2
head = head.next
return head