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.
/**
* 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* a = new ListNode(0),*b=a;
while( l1 != NULL && l2 != NULL){
if(l1->val < l2->val){
a->next = l1;
a = l1;
l1=l1->next;
}
else {
a->next = l2;
a = l2;
l2 = l2->next;
}
}
if(l1 == NULL) a->next = l2;
else a->next = l1;
return b->next;
}
};
本文介绍了一种合并两个已排序的链表的方法,并通过拼接节点的方式返回一个新的排序链表。该方法首先创建一个虚拟头节点,然后遍历两个输入链表,比较当前节点的值并连接较小值节点到新链表,直至其中一个链表遍历完毕。

被折叠的 条评论
为什么被折叠?



