題目描述
題目鏈接:https://leetcode.cn/problems/merge-two-sorted-lists/description/
思路
-
兩個鏈表都是升序鏈表,新建一個鏈表,引入偽頭節(jié)點(diǎn)作為輔助節(jié)點(diǎn),將各節(jié)點(diǎn)添加到偽節(jié)點(diǎn)之后,再用一個cur節(jié)點(diǎn)指向新鏈表的末尾
-
遍歷兩個鏈表,對比每個節(jié)點(diǎn)值,將更小的鏈表節(jié)點(diǎn)加入到新鏈表中文章來源:http://www.zghlxwxcb.cn/news/detail-648826.html
-
如果其中一個鏈表未遍歷完,那就直接加入到新鏈表后面文章來源地址http://www.zghlxwxcb.cn/news/detail-648826.html
實(shí)現(xiàn)代碼
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode list = new ListNode(); //偽頭節(jié)點(diǎn)
ListNode cur = list; // cur 指向新鏈表的末尾
while (list1 != null && list2 != null) {
if (list1.val < list2.val) {
cur.next = list1; // 把 list1 加到新鏈表中
list1 = list1.next;
} else {
cur.next = list2; // 把 list2 加到新鏈表中
list2 = list2.next;
}
cur = cur.next;
}
cur.next = list1 != null ? list1 : list2; // 拼接剩余的鏈表
return list.next;
}
}
到了這里,關(guān)于Leetcode 21. 合并兩個有序鏈表的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!