# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
head=ListNode(0)
cur=head
cur1=l1
cur2=l2
while cur1 and cur2:
if cur1.val<=cur2.val:
cur.next=cur1
cur1=cur1.next
else:
cur.next=cur2
cur2=cur2.next
cur=cur.next
if cur1:
cur.next=cur1
if cur2:
cur.next=cur2
return head.next
附上python链表学习笔记
class Node:
'''
data: 节点保存的数据
_next: 保存下一个节点对象
'''
def __init__(self, data, pnext=None):
self.data = data
self._next = pnext
def __repr__(self):
'''
用来定义Node的字符输出,
print为输出data
'''
return str(self.data)
#插入一个节点的代码
def insert(self, index, dataOrNode):
if self.isEmpty():
print "this chain tabale is empty"
return
if index < 0 or index >= self.length:
print "error: out of index"
return
item = None
if isinstance(dataOrNode, Node):
item = dataOrNode
else:
item = Node(dataOrNode)
if index == 0:
item._next = self.head
self.head = item
self.length += 1
return
j = 0
node = self.head
prev = self.head
while node._next and j < index:
prev = node
node = node._next
j += 1
if j == index:
item._next = node
prev._next = item
self.length += 1