Leetcode Problem.21—Merge Two Sorted Lists

来源:互联网 发布:linux 进程逻辑地址 编辑:程序博客网 时间:2024/05/24 05:51

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.

My C++ solution!

<span style="font-size:14px;">ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {    ListNode *l=new ListNode(0);ListNode *t=l;if(l1==NULL&&l2==NULL)return l1;else if(l1==NULL)return l2;else if(l2==NULL)return l1;else{while(l1||l2){if(l1&&l2){ListNode *temp=(l1->val>l2->val)?l2:l1;t->next=temp;t=t->next;if(l1->val>l2->val)l2=l2->next;elsel1=l1->next;}else if(l1){ListNode *temp=l1;t->next=temp;t=t->next;l1=l1->next;}else{ListNode *temp=l2;t->next=temp;t=t->next;l2=l2->next;}}}return l->next;}</span>


0 0