/** * struct ListNode { * int val; * struct ListNode *next; * }; */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pHead1 ListNode类 * @param pHead2 ListNode类 * @return ListNode类 */ #include <math.h> #include <stdlib.h> struct ListNode* Merge(struct ListNode* pHead1, struct ListNode* pHead2) { // write code here struct ListNode* pHead = (struct ListNode*)malloc(sizeof(struct ListNode)); struct ListNode* head = pHead; struct ListNode* pre = pHead; // 检查是否有链表为空 if(pHead1 == NULL) { return pHead2; } if(pHead2 == NULL) { return pHead1; } // 使用两个指针分别指向两个链表,进行值比较 while (pHead1 != NULL && pHead2 != NULL) { if (pHead1->val < pHead2->val) { pHead->val = pHead1->val; struct ListNode* temp = (struct ListNode*)malloc(sizeof(struct ListNode)); pHead->next = temp; pre = pHead; // pre指针指向当前节点的上一个节点 pHead = pHead->next; pHead1 = pHead1->next; } else { pHead->val = pHead2->val; struct ListNode* temp = (struct ListNode*)malloc(sizeof(struct ListNode)); pHead->next = temp; pre = pHead; pHead = pHead->next; pHead2 = pHead2->next; } } if(pHead1 == NULL) { pre->next = pHead2; // 接上另一个没遍历完的后续系节点 } else { pre->next = pHead1; } return head; }