思路:
链表初始化
class ListNode :
def __init__ ( self, x) :
self. data = x
self. next = None
def Merge ( ahead, bhead) :
if not ahead:
return bhead
if not bhead:
return ahead
p1= ahead
p2= bhead
if p1. data<= p2. data:
newhead= listNode( p1. data)
p1= p1. next
else :
newhead= listNode( p2. data)
p2= p2. next
p= newhead
while p1 and p2:
if p1. data<= p2. data:
p. next = listNode( p1. data)
p= p. next
p1= p1. next
else :
p. next = listNode( p2. data)
p= p. next
p2= p2. next
'''
# 也可以如下写法
if p1:
p.next=p1
if p2:
p.next=p2
'''
while p1:
p. next = listNode( p1. data)
p= p. next
p1= p1. next
while p2:
p. next = listNode( p2. data)
p= p. next
p2= p2. next
return newhead
```python
class listOp:#链表基本操作
def __init__(self):
self.head=None
def tailInsert(self,data):
# 尾插法创建链表
# 1->2->3->None
node=listNode(data)
if not self.head:
self.head=node
return self.head
cur=self.head
while cur.next:
cur=cur.next
cur.next=node
return self.head
def headInsert(self,data):# 头插法创建链表
node=listNode(data)
if not self.head:
self.head=node
return
node.next=self.head
self.head=node
return self.head
def travel(self):#链表遍历
cur =self.head
while cur:
print(cur.data)
cur=cur.next