21. Merge Two Sorted Lists合并两个有序链表
Posted hozhangel
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了21. 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.
不申请新的节点(把两个链表的节点接起来)
提交通过:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode v(0),*pre = &v,*p = pre; // pre带头结点 while(l1 != NULL && l2 != NULL){ if(l1->val > l2 ->val){ p->next = l2; l2 = l2->next; p = p->next; } else{ p->next = l1; l1 = l1->next; p = p->next; } } if(l1 == NULL ) p->next = l2; else p->next = l1; return pre->next; }
以上是关于21. Merge Two Sorted Lists合并两个有序链表的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] 21. Merge Two Sorted Lists_Easy tag: Linked List