算法--合并两个有序链表
生活随笔
收集整理的這篇文章主要介紹了
算法--合并两个有序链表
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
? ? ? 有兩種方法,迭代和遞歸。
? ? ? 迭代:
//不帶頭結點 Node * Merge(Node *head1 , Node *head2){//判空if ( head1 == NULL)return head2 ;if ( head2 == NULL)return head1 ;//頭結點Node *head = NULL ;//分別指向兩個鏈表Node *p1 = NULL;Node *p2 = NULL;//head指向較小值的那個鏈表if ( head1->data < head2->data ){head = head1 ;p1 = head1->next;p2 = head2 ;}else{head = head2 ;p2 = head2->next ;p1 = head1 ;}//當前排序好的鏈表的末尾節(jié)點Node *pcurrent = head ;while ( p1 != NULL && p2 != NULL){if ( p1->data <= p2->data ){pcurrent->next = p1 ;pcurrent = p1 ;p1 = p1->next ;}else{pcurrent->next = p2 ;pcurrent = p2 ;p2 = p2->next ;}}//還有一方?jīng)]有遍歷完的情況if ( p1 != NULL )pcurrent->next = p1 ;if ( p2 != NULL )pcurrent->next = p2 ;return head ; }時間復雜度:O(n+m),m和n分別為兩個鏈表的長度,因為兩個鏈表都要遍歷到
空間復雜度:O(1)
?
遞歸:
Node * MergeRecursive(Node *head1 , Node *head2){//判空if ( head1 == NULL )return head2 ;if ( head2 == NULL)return head1 ;Node *head = NULL ;if ( head1->data < head2->data ){head = head1 ;//每次遞歸都返回head->next,head表示當前節(jié)點,一個局部變量head->next = MergeRecursive(head1->next,head2);}else{head = head2 ;head->next = MergeRecursive(head1,head2->next);}return head ; }時間復雜度:O(n+m),每個節(jié)點都要遍歷到
空間復雜度:O(n+m),遞歸需要消耗??臻g,大小就是m+n
?
力扣的迭代代碼更為簡潔
ListNode* mergeTwoLists(ListNode *a, ListNode *b) {if ((!a) || (!b)) return a ? a : b;ListNode head, *tail = &head, *aPtr = a, *bPtr = b;while (aPtr && bPtr) {if (aPtr->val < bPtr->val) {tail->next = aPtr; aPtr = aPtr->next;} else {tail->next = bPtr; bPtr = bPtr->next;}tail = tail->next;}tail->next = (aPtr ? aPtr : bPtr);return head.next; }
?
代碼地址:https://www.cnblogs.com/fangyukuan/archive/2010/09/18/1829871.html
?
總結
以上是生活随笔為你收集整理的算法--合并两个有序链表的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ctrl+f5 强刷新
- 下一篇: 算法--删除链表的倒数第N个节点