链表题没有太多算法,看似简单,但是一定要有耐心和细心。最重要的就是搞清楚指针到底指向哪里,要在纸上理清楚,再敲代码
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pHead1 ListNode类
* @param pHead2 ListNode类
* @return ListNode类
*/
ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
// write code here
//再创建一个新的链表
ListNode* head = new ListNode (0);
ListNode* head_head = head;
ListNode* p1 = pHead1;
ListNode* p2 = pHead2;
while (p1 != NULL && p2 != NULL) {
ListNode* t1 = p1->next;
ListNode* t2 = p2->next;
if (p1->val <= p2->val) {
head->next = p1;
head = p1;
p1 = t1;
}
else {
head->next = p2;
head = p2;
p2 = t2;
}
}
if (p1 == NULL) {
head->next = p2;
}
else if (p2 == NULL) {
head->next = p1;
}
return head_head->next;
}
};

京公网安备 11010502036488号