题目意思:对两个递增链表进行归并排序
思路:没什么好说的,二路归并
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { 12 ListNode* head=new ListNode(0); 13 ListNode* p=head; 14 while(l1&&l2){ 15 if(l1->val<=l2->val){ 16 p->next=l1; 17 l1=l1->next; 18 p=p->next; 19 } 20 else{ 21 p->next=l2; 22 l2=l2->next; 23 p=p->next; 24 } 25 } 26 if(l1)p->next=l1; 27 if(l2)p->next=l2; 28 return head->next; //第一个节点去掉 29 } 30 };
时间: 2024-11-08 09:44:32