题解 | #合并两个排序的链表#
合并两个排序的链表
https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337
/* 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 && pHead2 == NULL) return NULL; if(pHead1 == NULL) return pHead2; if(pHead2 == NULL) return pHead1; struct ListNode* p = (struct ListNode*)malloc(sizeof(struct ListNode)); p->val = -1; struct ListNode *list = p; while(pHead1 != NULL && pHead2 != NULL){ if(pHead1->val <= pHead2->val){ list->next = pHead1; list = list->next; pHead1 = pHead1->next; } else{ list->next = pHead2; list = list->next; pHead2 = pHead2->next; } } if(pHead1 == NULL){ list->next = pHead2; return p->next; } list->next = pHead1; return p->next; } };