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

83 lines
3.5 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

> **[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/)
```
1->2->4, 1->3->4
1->1->2->3->4->4
```
AC
headpreheadpre.next
![](https://cdn.jsdelivr.net/gh/tan45du/photobed@master/photo/合并数组.216f4nn4lti8.gif)
****
Java Code:
```java
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
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;
}
}
```
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;
}
};
```