25合并两个排序链表

廉价感情. 提交于 2020-03-03 16:07:08

创建两个同地址表头,再将其中一个对两个链表进行排序
返回另一个表头->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)
    {
    ListNode *l3 = new ListNode(sizeof(ListNode));
    ListNode *tem=l3;

    while(l1!=NULL&&l2!=NULL)
    {

    if(l1->valval)
    {
    tem->next=l1;
    tem=tem->next;
    l1=l1->next;
    }
    else
    {
    tem->next=l2;
    tem=tem->next;
    l2=l2->next;
    }
    }
    if(l1!=NULL)tem->next=l1;
    if(l2!=NULL)tem->next=l2;

    return l3->next;
    }
    };

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!