class MergeList:
def __init__(self):
self.head = None
def mergeList2(self, a, b):
if a == None:
return b
if b == None:
return a
# 把两个链表头中较小的节点赋值给result
if a.data < b.data:
result = a
# 因为这里是用downNode指针存储扁平化后的链表,所以不是nextNode
result.downNode = self.mergeList2(a.downNode, b)
else:
result = b
result.downNode = self.mergeList2(a, b.downNode)
return result
def flatten(self, head):
if not head or not head.nextNode:
return head
head.nextNode = self.flatten(head.nextNode)
'''
把head节点对应的链表与右边的链表合并
递归遍历到结点15后的整体递归过程如下:
(15, 30) -> result = 15, result.down=22
(22, 30) -> result = 22, result.down=30
(50, 30) -> result = 30, result.down=39
(50, 39) -> result = 39, result.down=40
(50, 40) -> result = 40, result.down=50
(50, 55) -> result = 50, result.down=55
(None,55)-> result = 55,
最终对于节点15,得到了如下链表:
15->22->30->39->40->50->55
15节点被赋予给11节点的右节点
'''
head = self.mergeList2(head, head.nextNode)
return head
def printList(self):
curr = self.head
result = ""
while curr:
if result:
result += "->" + str(curr.data)
else:
result = str(curr.data)
curr = curr.downNode
print(result)
def costructList(arrList):
if not arrList:
return
head = buildList(arrList[0])
current = head
for i, arr in enumerate(arrList):
if 0 == i:
continue
newNode = buildList(arr)
current.nextNode = newNode
current = newNode
return head
class Node(object):
def __init__(self, data=None, nextNode=None, downNode=None):
self.data = data
self.nextNode = nextNode
self.downNode = downNode
def buildList(arr):
if not arr:
return
head = Node(arr[0])
current = head
for i, data in enumerate(arr):
if 0 == i:
continue
newNode = Node(data)
current.downNode = newNode
current = newNode
return head
def process():
arr1 = [3, 6, 8, 31]
arr2 = [11, 21]
arr3 = [15, 22, 50]
arr4 = [30, 39, 40, 55]
arr = [arr1, arr2, arr3, arr4]
head = costructList(arr)
megList = MergeList()
result = megList.flatten(head)
megList.head = result
megList.printList()
if __name__ == "__main__":
process()