题解 | #合并两个排序的链表#
合并两个排序的链表
https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pHead1 ListNode类 * @param pHead2 ListNode类 * @return ListNode类 */ #include <stdlib.h> struct ListNode* Merge(struct ListNode* pHead1, struct ListNode* pHead2 ) { // write code here #if 0 if(pHead1 == NULL) return pHead2; else if ( pHead2 == NULL) return pHead1; else if (pHead1 == NULL && pHead2 == NULL) return NULL; struct ListNode *head = malloc(sizeof(struct ListNode));//新链表头结点 struct ListNode *p = head; while (pHead1 != NULL && pHead2 != NULL) { if(pHead1 -> val >= pHead2 -> val) //pHead1链表节点值 大于 pHead2链表值 取 链表phead2节点 { p->next = pHead2; pHead2 = pHead2->next; //取完向后走一步 } else //取phead1链表节点值 { p->next = pHead1; pHead1 = pHead1->next; } p = p->next; } // if(pHead1) // p->next = pHead1; // if(pHead2) // p->next = pHead2; p->next = (pHead1?pHead1:pHead2); return head->next;//因为动态分配一个节点,并且next指向其他链表头结点,所以head值无效 #endif //递归版本 if(pHead1 == NULL) return pHead2; if(pHead2 ==NULL) return pHead1; // 根据值的大小决定哪个链表节点作为当前节点 if (pHead1->val <= pHead2->val) { pHead1->next = Merge(pHead1->next, pHead2); return pHead1; } else { pHead2->next = Merge(pHead1, pHead2->next); //pHead2 设为当前节点 设置当前节点的下一个节点 递归 return pHead2; } }