# LC 21. Merge Two Sorted Lists

## 题目描述

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

## 参考答案

 1 /**
2  * Definition for singly-linked list.
3  * struct ListNode {
4  *     int val;
5  *     ListNode *next;
6  *     ListNode(int x) : val(x), next(NULL) {}
7  * };
8  */
9 class Solution {
10 public:
11     ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
12         ListNode res(0); // content
13         ListNode* cur = &res; // pointer cur = taking addree of res
14         // *content. &pointer->
15
16         while(l1&&l2){
17             if(l1->val > l2 ->val){
18                 cur->next = l2;
19                 l2 = l2->next;
20             }else{
21                 cur->next = l1;
22                 l1 = l1->next;
23             }
24             cur = cur->next;
25         }
26         cur->next = l2?l2:l1;
27         return res.next;
28     }
29 };

## 答案解析

posted @ 2019-10-07 17:34  schaffen  阅读(52)  评论(0编辑  收藏