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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
ListNode *vHead = new ListNode(-1);//virtualHead;
ListNode *tmp = vHead;
ListNode *tmp_A = l1;
ListNode *tmp_B = l2;
while(tmp_A && tmp_B)
{
if(tmp_A->val<=tmp_B->val)
{
tmp->next = tmp_A;
tmp_A = tmp_A->next;
}
else
{
tmp->next = tmp_B;
tmp_B = tmp_B->next;
}
tmp = tmp->next;
}
while(tmp_A)
{
tmp->next = tmp_A;
tmp_A = tmp_A->next;
tmp = tmp->next;
}
while(tmp_B)
{
tmp->next = tmp_B;
tmp_B = tmp_B->next;
tmp = tmp->next;
}
if(!vHead->next) return NULL;
else return vHead->next;
}
};
本文介绍了一种将两个已排序的链表合并为一个新排序链表的方法。通过比较两个链表节点的值,选择较小的节点加入到新链表中,最终形成完整的有序链表。文章提供了一个C++实现示例。
1470

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



