请教一个关于链表的问题

2018-09-06 18:12:00 +08:00
 NaVient

假如我现在有两个链表 A, B
A 链表: 1 -> 3 -> 5
B 链表: 2 -> 4 -> 6

最终合并结果是 链表: 1 -> 2 -> 3 -> 4 -> 5 -> 6 该如何做?

2427 次点击
所在节点    Python
12 条回复
frandy
2018-09-06 18:26:42 +08:00
a = [1,3,5]
b = [2,4,6]
c = a+b
c.sort()
print(c)
meik2333
2018-09-06 18:33:46 +08:00
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (l1 == nullptr) {
return l2;
} else if (l2 == nullptr) {
return l1;
}
auto *head = new ListNode(0);
auto *cur = head;
while (l1 and l2) {
if (l1->val < l2->val) {
cur->next = l1;
l1 = l1->next;
} else {
cur->next = l2;
l2 = l2->next;
}
cur = cur->next;
}
cur->next = l1 ? l1 : l2;
cur = head->next;
delete head;
return cur;
}
cjw1115
2018-09-06 18:36:45 +08:00
@frandy 这操作还是很皮的
ihainan
2018-09-06 18:38:25 +08:00
dbw9580
2018-09-06 18:53:07 +08:00
list(itertools.chain.from_iterable(zip(a,b)))
zyp0921
2018-09-06 18:54:02 +08:00
比大小呗- -
anonymous256
2018-09-06 18:57:03 +08:00
c = [*a, *b]
c.sort()
print(c)
seven2016
2018-09-06 19:01:51 +08:00
链表常规题--归并

![归并]( https://zhimap.com/res/9/7/1532918487486844736.png)
someonedeng
2018-09-06 21:25:52 +08:00
作业要自己做。
stargazer
2018-09-06 22:47:06 +08:00
合并有序链表,,,
tt67wq
2018-09-07 10:09:35 +08:00
归并排序似乎就是这个
Cukuyo
2018-09-07 14:16:55 +08:00
作业要自己做

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/486849

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX