您的位置:首页 > 其它

Leetcode Merge Two Sorted Lists

2013-10-13 13:11 295 查看
将两个有序(默认是升序)的链表合并,由于要返回head结点,所以一开始要增加一个dummy(虚拟的)结点,即cur一开始new出来的。

如果head结点为空的话,设置head结点为cur->next。

/**
* 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) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(l1 == NULL)  return l2;
if(l2 == NULL)  return l1;
ListNode *head = NULL, *cur = new ListNode(1);
while(l1 != NULL || l2 != NULL){
if(l1 == NULL || (l1 != NULL && l2 != NULL && l2->val <= l1->val)){
cur->next = new ListNode(l2->val);
l2 = l2->next;
}
else if(l2 == NULL || (l1 != NULL && l2 != NULL && l2->val > l1->val)){
cur->next = new ListNode(l1->val);
l1 = l1->next;
}
if(head == NULL)    head = cur->next;
cur = cur->next;
}
return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  merge dummy 合并