对两个链表的排序和合并

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

首先定义链表节点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;
			}
		}
	}

}


你可能感兴趣的:(struct,null)