[LeetCode] #21 Merge Two Sorted Lists

it2022-05-05  127

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.

本题就是简单的链表合成。时间:14ms

我的代码:

/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if (l1 == NULL) return l2; if (l2 == NULL) return l1; ListNode *p1, *p2, *pHead, *pNext; p1 = l1, p2 = l2, pHead = pNext; while (p1!=NULL&&p2!=NULL){ if (p1->val <= p2->val){ pNext->next = p1; p1 = p1->next; } else{ pNext->next = p2; p2 = p2->next; } pNext = pNext->next; } while (p1!=NULL){ pNext->next = p1; p1 = p1->next; pNext = pNext->next; } while (p2!=NULL){ pNext->next = p2; p2 = p2->next; pNext = pNext->next; } return pHead->next; } };

 

转载于:https://www.cnblogs.com/Scorpio989/p/4452573.html


最新回复(0)