# 两个有序链表如何合并后输出一个有序链表

0

`````` public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

}

public static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;

}
}

}``````
ycyzharry | 高人七级 | 园豆：25513

0

ycyzharry | 园豆：25513 (高人七级) | 2019-07-30 15:56

@ycyzharry: 我写了一段代码，满足你的需求，不过没有测其它的极端情况，仅供参考：

``````class Node(object):
def __init__(self, val):
self.__val = val
self.__next = None

@property
def val(self):
return self.__val

@property
def next(self):
return self.__next

@next.setter
def next(self, next):
self.__next = next

def __str__(self):
display = ''
node = self
while node:
if display == '':
display = str(node.val)
else:
display = display + '->' + str(node.val)
node = node.next
return display

def merge(node1, node2):
''' 合并两个链表，保持有序性'''

newnode = None

if node1 == None:
newnode = node2
elif node2 == None:
newnode = node1
else:
if node1.val < node2.val:
newnode = Node(node1.val)
node1 = node1.next
else:
newnode = Node(node2.val)
node2 = node2.next

currentnode = newnode

while True:
if node1 == None and node2 == None:
break
else:
if node1 == None:
currentnode.next = Node(node2.val)
currentnode = currentnode.next
node2 = node2.next
elif node2 == None:
currentnode.next = Node(node1.val)
currentnode = currentnode.next
node1 = node1.next
else:
if node1.val < node2.val:
currentnode.next = Node(node1.val)
currentnode = currentnode.next
node1 = node1.next
else:
currentnode.next = Node(node2.val)
currentnode = currentnode.next
node2 = node2.next
return newnode

if __name__ == "__main__":

node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
node4 = Node(4)
node5 = Node(5)
node8 = Node(8)

node1.next = node3
node3.next = node4

node2.next = node5
node5.next = node8

print(node1) # 1->3->4
print(node2) # 2->5->8

newnode = merge(node1, node2)
print(newnode) # 1->2->3->4->5->8
``````

@会长: 谢谢

ycyzharry | 园豆：25513 (高人七级) | 2019-07-30 19:08

java版本：

``````public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode listNode = new ListNode(0);
ListNode firstNode = listNode;

while (l1 != null && l2 != null) {
if (l1.val <= l2.val) {
listNode.next = l1;
l1 = l1.next;
} else {
listNode.next = l2;
l2 = l2.next;
}
listNode = listNode.next;
}
while (l1 != null) {
listNode.next = l1;
l1 = l1.next;
listNode = listNode.next;
}
while (l2 != null) {
listNode.next = l2;
l2 = l2.next;
listNode = listNode.next;
}
return firstNode.next;
}``````

java实现两个有序单链表合并

ycyzharry | 园豆：25513 (高人七级) | 2019-08-01 13:38

0

1

a.concat(b).sort()

Eric.luo | 园豆：853 (小虾三级) | 2019-07-30 15:45

您需要登录以后才能回答，未注册用户请先注册