牛客《剑指Offer》-- 合并两个排序的链表

来源:互联网 发布:研究生软件辅导机构 编辑:程序博客网 时间:2024/06/05 09:11

题目:https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337?tpId=13&tqId=11169&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

题目描述

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

思路

链表合并

/*struct ListNode {    int val;    struct ListNode *next;    ListNode(int x) :            val(x), next(NULL) {    }};*/class Solution {public:    ListNode* Merge(ListNode* pHead1, ListNode* pHead2)    {        ListNode *phead = new ListNode(0);        ListNode *tmphead = phead;        while(pHead1!=NULL && pHead2!=NULL){            if(pHead1->val>pHead2->val){                tmphead->next = pHead2;                pHead2 = pHead2->next;            }            else{                tmphead->next = pHead1;                pHead1 = pHead1->next;            }            tmphead = tmphead->next;        }        while(pHead1!=NULL){            tmphead->next = pHead1;            pHead1 = pHead1->next;            tmphead = tmphead->next;        }        while(pHead2!=NULL){            tmphead->next = pHead2;            pHead2 = pHead2->next;            tmphead = tmphead->next;        }        tmphead->next = NULL;        return phead->next;    }};
原创粉丝点击