有关链表的经典算法

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
点赞