LeetCode/21. Merge Two Sorted Lists.md
2018-09-19 18:46:03 +08:00

45 lines
1.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [21. Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/description/)
# 思路
合并两个已有序的链表注意题目给的链表没有头结点所以为了操作方便可以自己设一个头结点最后返回头结点的下一个节点即可。两个链表的工作指针就用传进来的l1和
l2即可。
# C++
```
/**
* 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;
}
};
```