合并两个排序的链表

来源:互联网 发布:游戏破解软件大全 编辑:程序博客网 时间:2024/06/07 04:23

合并两个排序的链表

  • 时间限制:1秒
  • 空间限制:32768K
  • 本题知识点: 链表

题目描述

输入两个单调递增的链表,输出两个链表合成后的链表,
当然我们需要合成后的链表满足单调不减规则。

牛客网题目链接:点击这里

VS2010调试代码(完整版)

#include<iostream>using namespace std;struct ListNode {    int val;    struct ListNode *next;    ListNode(int x) :            val(x), next(NULL) {    }};class Solution {public:    ListNode* Merge(ListNode* pHead1, ListNode* pHead2)    {        ListNode* p1=NULL;        ListNode* p2=NULL;        ListNode* ML=NULL;        ListNode* temp1=NULL;        ListNode* temp2=NULL;        //建一个空的头结点        ListNode* h=(ListNode*)malloc(sizeof(ListNode));        h->next=pHead1;        //准备索引指针        p1=h;        p2=pHead2;        while(p1!=NULL && p2!=NULL)        {            while(p1->next!=NULL && (p1->next)->val < p2->val)                p1=p1->next;            temp1=p1->next;            p1->next=p2;            p1=temp1;            if(temp1==NULL) return h->next;            while(p2->next!=NULL && (p2->next)->val <= temp1->val)                p2=p2->next;            temp2=p2->next;            p2->next=temp1;            p2=temp2;        }        return h->next;    }};ListNode* CreatList(int length)  //输入元素个数,创建链表{    ListNode* L=NULL;    ListNode* p=NULL;    ListNode* t=NULL;    int tmpL=0;    for(int i=0; i<length; i++)    {        if(i==0)        {            cout<<"输入第"<<i+1<<"个元素:";            cin>>tmpL;            p=new ListNode(tmpL);            L=p;        }        else        {            cout<<"输入第"<<i+1<<"个元素:";            cin>>tmpL;            t=new ListNode(tmpL);            p->next=t;            p=p->next;        }    }    return L;}void PrintList(ListNode* pL)  //输出链表{    ListNode* p=pL;    if(p==NULL) cout<<"空";    while(p!=NULL)    {        cout<<p->val<<"->";        p=p->next;    }    cout<<endl<<endl;}int main(){    Solution s1;    ListNode* L1=NULL;    ListNode* L2=NULL;    int length1=0,length2=0;    while(1)    {    cout<<"链表L1的元素个数:";    cin>>length1;    L1=CreatList(length1);    cout<<"输出链表L1:";    PrintList(L1);    cout<<"链表L2的元素个数:";    cin>>length2;    L2=CreatList(length2);    cout<<"输出链表L2:";    PrintList(L2);    cout<<"合并链表L1和L2"<<endl;    ListNode* Ls=NULL;    Ls=s1.Merge(L1,L2);    PrintList(Ls);    }}//设计测试用例://1. L1=[1 3]; L2=[2 4]  通过//2. L1=[1]; L2=[2 4]  通过//3. L1=[]; L2=[2 3]  通过//4. L1=[1]; L2=[] 通过//5. L1=[2 4 5]; L2=[1] 只输出了2 4 5,修改后通过//6. L1=[2 4 5]; L2=[0 1]   只输出了2 4 5,修改后通过//7. L1=[2 2 2 3 4]; L2=[1 2 2 5]  L2的122没有输出,修改后通过//2.的bug通过在程序中添加判断L1末尾为空的语句,直接返回链表。//5.6.7.的bug通过将程序中的return pHead改为return h->next,//  避免了插在头部的数据不被返回。

说明:自己编写测试用例,调完bug后,提交一次通过,说明测试用例的逻辑还可以,基本能够覆盖全部情况。Well Done。

牛客网提交通过图片:

这里写图片描述

0 0
原创粉丝点击