合并两个有序链表,合并后依然有序

问题描述:
合并两个有序链表,合并后依然有序
实现思路:
先比较两个有序链表的头结点,将值最小的头结点作为新链表的头结点,设置两个新的指针,分别遍历两个链表,将值较小的结点尾插到新的链表中;
具体代码实现如下:

typedef int DataType;
typedef struct SListNode{
    struct SListNode* _next;
    DataType _data;
}SListNode,*pSListNode;

pSListNode MergeList(pSListNode pHead1, pSListNode pHead2)
{

    pSListNode cur1 = pHead1;
    pSListNode cur2 = pHead2;
    pSListNode NewList = NULL;
    pSListNode tmp = NULL;
    if (pHead1 == NULL)
        return pHead2;
    if (pHead2 == NULL)
        return pHead1;
    if (cur1->_data <= cur2->_data)
    {
        NewList = cur1;
        cur1 = cur1->_next;
    }
    else
    {
        NewList = cur2;
        cur2 = cur2->_next;
    }
    tmp = NewList;
    while (cur1 != NULL && cur2 != NULL)
    {
        if (cur1->_data < cur2->_data)
        {
            tmp->_next = cur1;
            cur1 = cur1->_next;     
        }
        else
        {
            tmp->_next = cur2;
            cur2 = cur2->_next;
        }
        tmp = tmp->_next;
    }
    if (cur1)
        tmp->_next = cur1;
    if (cur2)
        tmp->_next = cur2;
    return NewList;
}

猜你喜欢

转载自blog.csdn.net/zl_8577/article/details/81052734
今日推荐