温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

合并两个有序的链表

发布时间:2020-07-15 11:33:17 来源:网络 阅读:229 作者:秋笙夏笛 栏目:编程语言
#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;
}

结果:

合并两个有序的链表

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI