您的位置:首页 > 其它

LeetCode(21)题解:Merge Two Sorted Lists

2015-06-18 23:16 330 查看
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代码:

/**
* 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 *p=new ListNode(0);
ListNode *q=p;
while(l1!=NULL && l2!=NULL){
if(l1->val<l2->val){
q->next=l1;
q=q->next;
l1=l1->next;
}
else{
q->next=l2;
q=q->next;
l2=l2->next;
}
}
if(l1!=NULL)
q->next=l1;
else
q->next=l2;
p=p->next;
return p;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: