有关链表的经典算法

NO.11

LinkedList ReverseSinglyLinkedList(LinkedList list)
{
    LinkedList  newList;    //新链表的头结点
    LNode       *tmp;       //指向list的第一个结点,也就是要摘除的结点

    //
    //参数为空或者内存分配失败则返回NULL
    //
    if (list == NULL || (newList = (LinkedList)malloc(sizeof(LNode))) == NULL)
    {
        return NULL;
    }

    //
    //初始化newList
    //
    newList->data = list->data;
    newList->next = NULL;

    //
    //依次将list的第一个结点放到newList的第一个结点位置
    //
    while (list->next != NULL)
    {
        tmp = newList->next;         //保存newList中的后续结点
        newList->next = list->next;       //将list的第一个结点放到newList中
        list->next = list->next->next;     //从list中摘除这个结点
        newList->next->next = tmp;        //恢复newList中后续结点的指针
    }

    //
    //原头结点应该释放掉,并返回新头结点的指针
    //
    free(list);
    return newList;
}
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;  
}  

转自:http://blog.sina.com.cn/s/blog_8961925401017ard.html
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值