/*
合并两个排序的链表
*/
#include<iostream>
#include<stack>
using namespace std;
struct ListNode{ //链表结点定义
int m_nValue;
ListNode *m_pNext;
};
void AddToTail(ListNode **pHead,int value){
ListNode *pNew=new ListNode();
pNew->m_nValue=value;
pNew->m_pNext=NULL;
// cout<<"插入:"<<pNew->m_nValue<<endl;
if(*pHead==NULL)
*pHead=pNew;
else{
ListNode *pNode=*pHead;
while(pNode->m_pNext!=NULL){
pNode=pNode->m_pNext;
}
pNode->m_pNext=pNew;
}
}
ListNode* CreateList(){
ListNode *head=NULL;
int input=0;
cout<<"请输入链表元素(0结束)\n";
cin>>input;
while(input!=0){
AddToTail(&head,input);
cin>>input;
}
return head;
}
void PrintList(ListNode *head){
while(head!=NULL){
cout<<head->m_nValue<<" ";
head=head->m_pNext;
}
cout<<endl;
}
ListNode * Merge(ListNode *pHead1,ListNode *pHead2){
if(pHead1==NULL)
return pHead2;
if (pHead2==NULL)
return pHead1;
ListNode *pMergeNode=NULL;
if (pHead1->m_nValue>=pHead2->m_nValue){
pMergeNode=pHead2;
pMergeNode->m_pNext=Merge(pHead1,pHead2->m_pNext);
}
else{
pMergeNode=pHead1;
pMergeNode->m_pNext=Merge(pHead1->m_pNext,pHead2);
}
return pMergeNode;
}
int main(){
ListNode *p1=NULL;
ListNode *p2=NULL;
p1=CreateList();
p2=CreateList();
ListNode *mergep=Merge(p1,p2);
PrintList(mergep);
}
合并两个排序链表
最新推荐文章于 2024-02-07 14:30:00 发布