Merge Two Sorted Lists[LEETCODE]

本文提供了一种方法来合并两个已排序的链表,并使用C++实现了一个解决方案。代码中详细解释了如何遍历链表并正确连接节点。

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.

 ====================================================================================

One thing to mark. The expression below is wrong,

1 cur_node = new NodeList(x);
2 cur_node = cur_node->next;

the proper expression should be:

cur_node->next = new ListNode(x);
cur_node = cur_node->next;

So the whole code will be like this. Remember that the root node IS NOT included into result.

 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 * result_root = new ListNode(0);                                                       
13         ListNode * cur_node = result_root;                                                              
14         while(NULL != l1 || NULL != l2) {                                                               
15             if(NULL == l1 || (NULL != l1 && NULL != l2 && l2->val <= l1->val)) {                        
16                 cur_node->next = new ListNode(l2->val);                                                 
17                 l2 = l2->next;                                                                          
18             }else{                                                                                      
19                 cur_node->next = new ListNode(l1->val);                                                 
20                 l1 = l1->next;                                                                          
21             }                                                                                           
22             cur_node = cur_node->next;                                                                  
23                                                                                                         
24         }                                                                                               
25         return result_root->next; 
26     }
27 };

 

转载于:https://www.cnblogs.com/scenix/p/3372458.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值