LeetCode/solutions/21. Merge Two Sorted Lists.md

45 lines
1.3 KiB
Markdown
Raw Permalink Normal View History

2018-09-19 10:46:03 +00:00
# [21. Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/description/)
# 思路
合并两个已有序的链表注意题目给的链表没有头结点所以为了操作方便可以自己设一个头结点最后返回头结点的下一个节点即可。两个链表的工作指针就用传进来的l1和
l2即可。
# C++
2019-09-13 15:08:41 +00:00
``` C++
2018-09-19 10:46:03 +00:00
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode *res = new ListNode(0); // 自己设一个头结点
ListNode *pre = res; // pre代表已排好序的链表的最后一个节点
while(l1 && l2){
if(l1 -> val <= l2 -> val){
pre -> next = l1;
l1 = l1 -> next;
}
else{
pre -> next = l2;
l2 = l2 -> next;
}
pre = pre -> next; // pre后移
}
// 跳出循环时l1和l2其中一个是NULL
if(l1) pre -> next = l1;
else pre -> next = l2;
// 释放头结点
ListNode *head = res;
res = head -> next;
head -> next = NULL;
delete head;
return res;
}
};
```