剑指offer-----16、合并两个有序链表
1、题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
2、分析
这道题之前也在leetcode上做过,附解析(https://blog.csdn.net/zl6481033/article/details/89191015)。
3、代码
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if(pHead1==NULL) return pHead2;
if(pHead2==NULL) return pHead1;
ListNode* newNode=(ListNode*) new ListNode(0);
ListNode* ptr1=pHead1;
ListNode* ptr2=pHead2;
ListNode* cur=newNode;
while(ptr1!=NULL&&ptr2!=NULL){
if((ptr1->val)<=(ptr2->val)){
cur->next=ptr1;
ptr1=ptr1->next;
}
else{
cur->next=ptr2;
ptr2=ptr2->next;
}
cur=cur->next;
}
if(ptr1==NULL) cur->next=ptr2;
if(ptr2==NULL) cur->next=ptr1;
return newNode->next;
}
};
4、相关知识点
链表的题目经常会用到一个新节点,使用新节点来进行操作。

浙公网安备 33010602011771号