algorithm-base/animation-simulation/链表篇/剑指Offer25合并两个排序的链表.md

126 lines
4.5 KiB
Java
Raw Normal View History

2021-03-20 08:57:12 +00:00
> **[tan45du_one](https://raw.githubusercontent.com/tan45du/tan45du.github.io/master/个人微信.15egrcgqd94w.jpg)** ,备注 github + 题目 + 问题 向我反馈
>
>
>
> <u>[****](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
#### [ Offer 25. ](https://leetcode-cn.com/problems/he-bing-liang-ge-pai-xu-de-lian-biao-lcof/)
2021-03-19 07:07:33 +00:00
2021-07-15 16:06:52 +00:00
****
2021-03-19 07:07:33 +00:00
```
1->2->4, 1->3->4
1->1->2->3->4->4
```
2021-07-14 05:14:56 +00:00
AC
2021-03-19 07:07:33 +00:00
2021-07-15 16:06:52 +00:00
headpre headpre.next
2021-03-19 07:07:33 +00:00
![](https://cdn.jsdelivr.net/gh/tan45du/photobed@master/photo/合并数组.216f4nn4lti8.gif)
2021-04-28 10:28:00 +00:00
****
Java Code:
2021-03-19 07:07:33 +00:00
```java
2021-04-28 10:28:00 +00:00
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
2021-03-19 07:07:33 +00:00
ListNode headpro = new ListNode(-1);
ListNode headtemp = headpro;
while (l1 != null && l2 != null) {
//接上大的那个
if (l1.val >= l2.val) {
headpro.next = l2;
l2 = l2.next;
}
else {
headpro.next = l1;
l1 = l1.next;
}
headpro = headpro.next;
}
headpro.next = l1 != null ? l1:l2;
return headtemp.next;
}
2021-04-28 10:28:00 +00:00
}
```
C++ Code:
```cpp
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode * headpro = new ListNode(-1);
ListNode * headtemp = headpro;
while (l1 != nullptr && l2 != nullptr) {
//接上大的那个
if (l1->val >= l2->val) {
headpro->next = l2;
l2 = l2->next;
}
else {
headpro->next = l1;
l1 = l1->next;
}
headpro = headpro->next;
}
headpro->next = l1 != nullptr ? l1: l2;
return headtemp->next;
}
};
2021-03-19 07:07:33 +00:00
```
2021-07-14 05:14:56 +00:00
JS Code:
```js
var mergeTwoLists = function(l1, l2) {
let headpro = new ListNode(-1);
let headtemp = headpro;
while (l1 && l2) {
//接上大的那个
if (l1.val >= l2.val) {
headpro.next = l2;
l2 = l2.next;
}
else {
headpro.next = l1;
l1 = l1.next;
}
headpro = headpro.next;
}
headpro.next = l1 != null ? l1:l2;
return headtemp.next;
};
```
Python Code:
2021-07-15 16:06:52 +00:00
```python
2021-07-14 05:14:56 +00:00
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
headpro = ListNode(-1)
headtemp = headpro
while l1 and l2:
#
if l1.val >= l2.val:
headpro.next = l2
l2 = l2.next
else:
headpro.next = l1
l1 = l1.next
headpro = headpro.next
headpro.next = l1 if l1 is not None else l2
return headtemp.next
```