合并两个排序的链表

来源:互联网 发布:软件注册授权系统 编辑:程序博客网 时间:2024/06/05 09:44
/*struct ListNode {    int val;    struct ListNode *next;    ListNode(int x) :            val(x), next(NULL) {    }};*/class Solution {public:    ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {        ListNode* temp1 = pHead1;        ListNode* temp2 = pHead2;        ListNode* head = new ListNode(0);        ListNode* tail = head;        while (temp1 != NULL && temp2 != NULL)        {            if (temp1->val <= temp2->val)            {                tail->next = temp1;                tail = tail->next;                temp1 = temp1->next;            }            else            {                tail->next = temp2;                tail = tail->next;                temp2 = temp2->next;            }        }        if (temp1 != NULL)        {            tail->next = temp1;        }        else if (temp2 != NULL)        {            tail->next = temp2;        }        tail = head->next;        delete head;        return tail;    }};
原创粉丝点击