首页 > 其他 > 详细

LeetCode(21):Merge Two Sorted Lists

时间:2015-06-18 23:54:38      阅读:326      评论:0      收藏:0      [点我收藏+]

https://leetcode.com/problems/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.

思路:

考察链表操作,没啥说的。

AC代码:

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

 

LeetCode(21):Merge Two Sorted Lists

原文:http://www.cnblogs.com/aezero/p/4587302.html

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