链表l1里面值是 1->3->4
链表l2里面值是 2->5->8
要求输出:1->2->3->4->5->8
代码如下:
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
}
public static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
}
链表1和链表2本身是有序的吗?如果是的话那就比较好做了。另外,你把node定义成了静态的?你确定是静态的?
本身有序
@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
我没猜错的话:你肯定是会写的,只是为了赶时间才提了这个问题,想让别人给你写。我偏偏不用C#写,让你再重写一遍,哈哈哈,我也是闲的蛋疼啊。
@会长: 谢谢
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;
}
思路:
第一个while循环,将 l1 和 l2 进行比较,谁小谁就合并到 listNode,直到 l1 或者 l2 为空
第二个while循环和第三个while循环,将 l1 或者 l2 剩下的节点合并到 listNode
最后返回的是 firstNode.next //头节点是不需要的
其他方案可参考:
java实现两个有序单链表合并
参见Linq。
a.concat(b).sort()