溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Linked List-Easy怎么將兩個排序的鏈表合并

發(fā)布時間:2021-12-18 15:49:52 來源:億速云 閱讀:120 作者:iii 欄目:大數(shù)據(jù)

這篇文章主要講解了“Linked List-Easy怎么將兩個排序的鏈表合并”,文中的講解內(nèi)容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“Linked List-Easy怎么將兩個排序的鏈表合并”吧!

將兩個排序的鏈表合并,返回一個新鏈表,返回的新鏈表也是排好序的。

解題思路:

  • 創(chuàng)建兩個鏈表,一個負責保存頭節(jié)點,一個負責記錄比較后的結(jié)果。

Language : c

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {struct ListNode* newlist = (struct ListNode *)malloc(sizeof(struct ListNode));struct ListNode* temp = (struct ListNode *)malloc(sizeof(struct ListNode));
    newlist = temp;while(l1 && l2){if(l1->val < l2->val){
            temp->next = l1;
            l1 = l1->next;
        }else{
            temp->next = l2;
            l2 = l2->next;
        }
        temp = temp->next;
    }
    temp->next = l1 ? l1 : l2;return newlist->next;
}

Language : cpp

/**
 * 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 newlist(INT_MIN);
        ListNode *temp = &newlist;if(l1 == NULL && l2 == NULL){
            return NULL;
        }if(l1 != NULL && l2 == NULL){
            return l1;
        }if(l1 == NULL && l2 != NULL){
            return l2;
        }while(l1 && l2){if(l1->val < l2->val){
                temp->next = l1;
                l1 = l1->next;
            }else{
                temp->next = l2;
                l2 = l2->next;
            }
            temp = temp->next;
        }
        temp->next = l1 ? l1 : l2;
        return newlist.next;
    }
};

Language:python

# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution(object):def mergeTwoLists(self, l1, l2):"""
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """result = cur = ListNode(0)while l1 and l2:if l1.val < l2.val:
                cur.next = l1
                l1 = l1.nextelse:
                cur.next = l2
                l2 = l2.next
            cur = cur.next
        cur.next = l1 or l2return result.next

感謝各位的閱讀,以上就是“Linked List-Easy怎么將兩個排序的鏈表合并”的內(nèi)容了,經(jīng)過本文的學習后,相信大家對Linked List-Easy怎么將兩個排序的鏈表合并這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關(guān)知識點的文章,歡迎關(guān)注!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI