对两个链表的排序和合并

首先,讲一下对于两个已排序链表的合并。源码如下:

首先定义链表节点node,用于保存数据data和下一个节点next:

struct node/*定义链表*/
{
int data;
struct node *next;
};

然后对两个已排序链表进行合并,返回合并好的链表:

node *unite_sort(node *head1, node *head2)
{
    node *head;
    node *cur;
    
    if (NULL == head1)
    {
        return head2;
    }
    if (NULL == head2)
    {
        return head1;
    }
    
    if (head1->data < head2->data)//找出最小的那个data
    {
        head = head1;
        head1 = head1->next;
    }
    else
    {
        head = head2;
        head2 = head2->next;
    }
	
    for (cur = head; head1 != NULL && head2 != NULL; )
    {
        if (head1->data < head2->data)
        {
            cur->next = head1;
            cur = head1;
            head1 = head1->next;
        }
        else
        {
            cur->next = head2;
            cur = head2;
            head2 = head2->next;
        }
    }
    
    cur->next = (NULL == head1) ? head2 : head1;//head1和head2至少有一个为空时,剩下的那个链表直接放在cur->next
    
    return head;
}

若两个链表都没有进行排序,则在合并排序之前,需要对两个链表分别进行排序:

void rank(struct node *node1, int count1)
{
	int i,temp = 0;
	struct node *_ptr;
	for (i = 0;i<count1 -1;++i)
	{
		for (_ptr = node1->next; _ptr->next != NULL; _ptr = _ptr->next)
		{
			if (_ptr->data > _ptr->next->data)
			{
				temp = _ptr->data;
				_ptr->data = _ptr->next->data;
				_ptr->next->data = temp;
			}
		}
	}

}


评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值