#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<stdlib.h>
#include"algorithm"
using namespace std;
//链表结点
typedef struct _ListNode{
int data;
struct _ListNode* next;
}ListNode;
//无头节点
ListNode* LinkList_Create(int *value, int num)
{
ListNode *pHead = (ListNode*)malloc(sizeof(ListNode));
ListNode *pTail = pHead;
pHead->data = value[0];
pHead->next = NULL;
for(int i = 1; i < num; i++)
{
ListNode *pCur = (ListNode*)malloc(sizeof(ListNode));
pCur->data = value[i];
pTail-> next= pCur;
pTail = pCur;
}
pTail->next = NULL;
return pHead;
}
void PrintNode(ListNode *head)
{
ListNode *p = head;
for(;p;p = p->next)
{
printf("%d ",p->data);
}
printf("\n");
}
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
//判断指针是否为空
if(pHead1 == NULL)
return pHead2;
else if(pHead2 == NULL)
return pHead1;
ListNode *pMergehead = NULL;
if(pHead1->data < pHead2->data)
{
pMergehead = pHead1;
pMergehead->next = Merge(pHead1->next, pHead2);
}
else
{
pMergehead = pHead2;
pMergehead->next = Merge(pHead1, pHead2->next);
}
return pMergehead;
}
int main()
{
int data1[3] = {2,3,6};
int data2[4] = {1,4,5,7};
ListNode* pHead1 = LinkList_Create(data1,3);
ListNode* pHead2 = LinkList_Create(data2,4);
PrintNode(pHead1);
PrintNode(pHead2);
ListNode *list = Merge(pHead1, pHead2);
PrintNode(list);
return 0;
}
4、合并两个有序链表
最新推荐文章于 2021-01-26 14:14:31 发布