zoukankan      html  css  js  c++  java
  • 单链表的合并

    循环 解法一:

    ListNode* MergeList(ListNode *L1,ListNode *L2)//合并两个单链表
    {
        ListNode *newHead=NULL;
        ListNode *tail=NULL;
        if(L1==NULL)
        {
            return L2;
        }
        if(L2==NULL)
        {
            return L1;
        }
        if(L1->_data < L2->_data)
        {
            newHead=L1;
            L1=L1->_next;
        }
        else
        {
            newHead=L2;
            L2=L2->_next;
        }
        tail=newHead;
        while(L1 && L2)
        {
            if(L1->_data < L2->_data)
            {
                tail->_next=L1;
                L1=L1->_next;
            }
            else
            {
                tail->_next=L2;
                L2=L2->_next;
            }
            tail=tail->_next;
        }
        if(L1)
        {
            tail->_next=L1;
        }
        if(L2)
        {
            tail->_next=L2;
        }
        return tail;
    }

    递归 解法二:

    ListNode* Merge1(ListNode *a,ListNode *b)
    {
        if(a==NULL)
            return b;
        if(b==NULL)
            return a;
        ListNode *newhead=new ListNode;
        if(a->val<=b->val)
        {
            newhead=a;
            newhead->next=Merge1(a->next,b);
        }
        else
        {
            newhead=b;
            newhead->next=Merge1(a,b->next);
        }
        return newhead;
    }
  • 相关阅读:
    构造函数
    Php基础知识测试题答案与解释
    bootstrap简介
    ajax删除数据(不跳转页面)
    ajax基础部分
    Jquery弹出窗口
    JSON
    Jquery之JSON的用法
    Jquery基本用法
    php购物车(练习)
  • 原文地址:https://www.cnblogs.com/home123/p/6764220.html
Copyright © 2011-2022 走看看