题解 | #合并两个排序的链表#
合并两个排序的链表
https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337
struct ListNode* Merge(struct ListNode* pHead1, struct ListNode* pHead2 ) { if(pHead1 == NULL) return pHead2; if(pHead2 == NULL) return pHead1; struct ListNode *head=NULL, *tail=NULL; //哨兵位的头结点 head=tail=(struct ListNode*)malloc(sizeof(struct ListNode)); while(pHead1 && pHead2) { if(pHead1->val < pHead2->val) { tail->next=pHead1; tail = pHead1; pHead1 = pHead1->next; } else { tail->next=pHead2; tail = pHead2; pHead2 = pHead2->next; } } if(pHead1) tail->next = pHead1; if(pHead2) tail->next = pHead2; struct ListNode* list = head->next; free(head); return list; }