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.
两个链表的数据融合,考虑小的在前面,大的在后面。
三种情况,1、当两者有一个是NULL,返回另外链表.
2、两者都不是NULL,小的插入新建的节点MergeList.(头),新建节点Pcurrent.他不停的往MegeList
3、有一个数NULL,就把那个节点放在Pcurrent后面。
实现代码
#ifndef H_Initial_LinkList_H
#define H_Initial_LinkList_H
#include <stdio.h>
#include <iostream>
using namespace std;
typedef struct ListNode
{
int val;
struct ListNode *next;
}Node;
void DisplayList(struct ListNode* newhead) ;
struct ListNode* CreatList(struct ListNode* newhead,int n) ;
#endif
#ifndef H_LinkList_h
#define H_LinkList_h
#include "manipulateList.h"
#include "Initial_LinkList.h "
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2);
#endif
#include <windows.h>
#include <stdio.h>
#include <iostream>
#include "manipulateList.h"
#include "Initial_LinkList.h "
int main()
{
Node *head=(Node*)malloc(sizeof(Node));
Node *p,*q;
p=(Node*)malloc(sizeof(Node));
int n,n1; //如何让申请的两个地址不在同一点
n=1;
//n1=4;
Node *q1=(Node*)malloc(sizeof(Node));
//*******链表赋值*********//
printf("输入节点1个数: ");
scanf("n = %d",&n);
q=CreatList(head, n); //可以没有返回值
cout<<"第一组链表 "<<endl;
DisplayList(q);
printf("输入节点2个数: ");
char ch;
// while ((ch=getchar())!=EOF&&ch!='\n')
// ;
cin>>n1;
//scanf("n1 = %d",&n1);
q1=CreatList(q1, n1); //可以没有返回值
//*******链表输出值*********//
cout<<"第二组链表 "<<endl;
DisplayList(q1);
Node *MerGreList=(Node*)malloc(sizeof(Node));
MerGreList=mergeTwoLists(q,q1);
DisplayList(MerGreList);
//cout<<"删除一个"<<key<<"之后的链表数据: "<<endl;
DisplayList();
free(p);
free(head);*/
return 0;
}
#include "manipulateList.h"
#include "Initial_LinkList.h "
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2)
{
if (l2==NULL)
{
return l1;
}
if (l1==NULL)
{
return l2;
}
//倒数,从小到大,把小的放前面
struct ListNode* MergedLists=NULL; //头节点
if (l1->val<=l2->val)
{
MergedLists=l1;
l1=l1->next; //为什么变0了?
MergedLists->next=NULL;
}
else
{
MergedLists=l2;
l2=l2->next;
MergedLists->next=NULL;
}
struct ListNode* pCurrent=(struct ListNode*)malloc(sizeof(struct ListNode));
pCurrent=MergedLists; //当前节点,指向MegedList
// pCurrent=pCurrent->next; //指向自己:::位以后的做准备
while (l1!=NULL&&l2!=NULL)
{
if (l1->val<l2->val)
{
pCurrent->next=l1; //接着下面
l1=l1->next;
// pCurrent->next=NULL;
}
else
{
pCurrent->next=l2; //接着下面
// pCurrent=l2; //
l2=l2->next;
//pCurrent->next=NULL;
}
pCurrent=pCurrent->next;
//pCurrent->next=pCurrent;
}
if (l1==NULL)
{
while(l2!=NULL)
{
pCurrent->next=l2; //接着下面
//pCurrent=l2;
l2=l2->next;
pCurrent=pCurrent->next;
pCurrent->next=NULL;
}
}
else
{
while(l1!=NULL)
{
pCurrent->next=l1; //接着下面
//pCurrent=l1;
l1=l1->next;
pCurrent=pCurrent->next;
pCurrent->next=NULL;
}
}
// pCurrent->next=NULL;
return MergedLists;
}