首页 > 其他 > 详细

LC 21. Merge Two Sorted Lists

时间:2019-10-07 17:47:26      阅读:89      评论:0      收藏:0      [点我收藏+]

题目描述

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 };

答案解析

新建一个空节点,不是地址,而是内容,然后将该内容对应的地址,附给一个cur指针。

进行loop

返回的时候,因为对于struct而言,提取成员时,内容使用 点,指针使用 -> 。

 

LC 21. Merge Two Sorted Lists

原文:https://www.cnblogs.com/kykai/p/11631384.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!