4、合并两个有序链表

#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;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值