mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 21. Merge Two Sorted Lists.md
This commit is contained in:
parent
3286d7a8d4
commit
b4c62b1273
44
21. Merge Two Sorted Lists.md
Normal file
44
21. Merge Two Sorted Lists.md
Normal file
@ -0,0 +1,44 @@
|
||||
# [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;
|
||||
}
|
||||
};
|
||||
```
|
Loading…
Reference in New Issue
Block a user