溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

合并兩個有序的鏈表

發(fā)布時間:2020-07-15 11:33:17 來源:網(wǎng)絡(luò) 閱讀:230 作者:秋笙夏笛 欄目:編程語言
#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;
}

結(jié)果:

合并兩個有序的鏈表

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI