合并两个有序的链表

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
 
struct Listnode
{
    int _value;
    Listnode* _next;
};
void Init(Listnode*& head)
{
    Listnode* cur =head;
    if(cur==NULL)
    {
        cur=(Listnode*)malloc(sizeof(Listnode));
        cur->_next=NULL;
        cur->_value=0;
    }
    head=cur;
}
 
void push(Listnode*& head,int value)
{
    Listnode* cur =head;
 
        while(cur->_next)
        {
            cur=cur->_next;
        }
        Listnode* tmp=NULL;
        tmp=(Listnode*)malloc(sizeof(Listnode));
        tmp->_next=NULL;
        tmp->_value=value;
        cur->_next=tmp;
     
         
 
}
void pop(Listnode* head)
{
    Listnode* cur=head;
    Listnode* prev=NULL;
    while(cur->_next!=NULL)
    {
        prev=cur;
        cur=cur->_next;
    }
    prev->_next=NULL;
    free(cur);
    cur=NULL;
}
void print(Listnode* head)
{
    Listnode* cur=head;
    while(cur)
    {
        printf("%d\n",cur->_value);
        cur=cur->_next;
    }
}
Listnode* reverse(Listnode* head)
{
	Listnode* newhead=NULL;
	if(head==NULL||head->_next==NULL)
	{
		return head;
	}
	while(head)
	{
		Listnode* tmp=head;
		head=head->_next;
		tmp->_next=newhead;
		newhead=tmp;
		
	}
	return newhead;
}
Listnode* merge(Listnode* head1,Listnode* head2)
{
	if(head1==NULL&&head2!=NULL)
	{
		return head2;
	}
	else if(head2==NULL&&head1!=NULL)
	{
		 return head1;
	}
	else if(head1==NULL&&head2==NULL)
	{
		return NULL;
	}
	Listnode* newhead=NULL;
	Init(newhead);
	head1=head1->_next;
	head2=head2->_next;
	Listnode* cur=newhead;
	while(head1&&head2)
	{
		if(head1->_value>head2->_value)
		{
			cur->_next=head2;
			cur=cur->_next;
			head2=head2->_next;
		}
		else
		{
			cur->_next=head1;
			cur=cur->_next;
			head1=head1->_next;
		}
	}
	if(head1==NULL&&head2!=NULL)
	{
		cur->_next=head2;
		cur=cur->_next;
	}
	else if(head2==NULL&&head1!=NULL)
	{
		cur->_next=head1;
		cur=cur->_next;
	}
	return newhead;
}

void test()
{
    Listnode* head=NULL;
    Init(head);
    push(head,1);
    push(head,3);
    push(head,5);
	push(head,7);
	push(head,9);

    /*pop(head);*/
     Listnode* head2=NULL;
    Init(head2);
    push(head2,0);
    push(head2,2);
    push(head2,4);
	push(head2,6);
	push(head2,8);
	push(head2,10);

	Listnode* newhead=merge(head,head2);
	print(newhead);
  

   
 
}
int main()
{
    test();
    system("pause");
    return 0;
}

结果:

wKioL1c0bK_Rjl7hAAAUv-XXhvo897.png

本文出自 “liveyoung” 博客,转载请与作者联系!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值