问题描述:
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
代码如下: 6ms
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) { if(!l1 && !l2) return NULL; struct ListNode *pList = (struct ListNode *)malloc(sizeof(struct ListNode)); struct ListNode *pNode = NULL; struct ListNode *pHead = pList; while(l1 && l2) { pNode = (struct ListNode *)malloc(sizeof(struct ListNode)); if(l1->val < l2->val) { pNode->val = l1->val; l1 = l1->next; } else { pNode->val = l2->val; l2 = l2->next; } pNode->next = NULL; pList->next = pNode; pList = pNode; } while(l1) { pNode = (struct ListNode *)malloc(sizeof(struct ListNode)); pNode->val = l1->val; pNode->next = NULL; pList->next = pNode; pList = pNode; l1 = l1->next; } while(l2) { pNode = (struct ListNode *)malloc(sizeof(struct ListNode)); pNode->val = l2->val; pNode->next = NULL; pList->next = pNode; pList = pNode; l2 = l2->next; } return pHead->next; }