Merge Two Sorted Lists
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.
解題思路:
這道題是我做的leetcode最容易的題目了。其中有個小技巧,就是在最開始的時候申請一個頭結點,然後在融合之後再刪除頭結點。這樣能夠讓代碼更加清晰。利用原有的空間,更加加快了效率,在leetcode跑的時間僅僅13ms。Talk is cheap, show you the cade:
/** * 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) { ListNode* head=new ListNode(0); ListNode* p = head; //指向融合的最後一個元素 while(l1!=NULL&&l2!=NULL){ if(l1->valval){ p->next=l1; p=l1; l1=l1->next; }else{ p->next=l2; p=l2; l2=l2->next; } } while(l1!=NULL){ p->next=l1; p=l1; l1=l1->next; } while(l2!=NULL){ p->next=l2; p=l2; l2=l2->next; } p->next = NULL; p=head; head=head->next; delete p; return head; } };