leetcodeの第21題、*Merge Two Sorted Lists
テーマ
Merge two sorted linked lists and return it as a new list.The new list shoud be made by splicing togethe the nodes of the first two lists.
考え方
二つの秩序チェーンを一つの秩序チェーンにまとめる。まず、より愚かで簡潔な方法を使用します。2つの順序付きチェーンテーブルを巡回したノードは、ノード値の大きさを比較し、より小さい値をターゲットチェーンテーブルに入れ、遍歴した後、もし2つのチェーンが残りのノードがあれば、すでに規則的であるため、ターゲットチェーンの最後のノードを挿入することができます。
コード
Python
Merge two sorted linked lists and return it as a new list.The new list shoud be made by splicing togethe the nodes of the first two lists.
考え方
二つの秩序チェーンを一つの秩序チェーンにまとめる。まず、より愚かで簡潔な方法を使用します。2つの順序付きチェーンテーブルを巡回したノードは、ノード値の大きさを比較し、より小さい値をターゲットチェーンテーブルに入れ、遍歴した後、もし2つのチェーンが残りのノードがあれば、すでに規則的であるため、ターゲットチェーンの最後のノードを挿入することができます。
コード
Python
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
head = ListNode(0)
cur = head
while(l1 != None and l2 != None):
# l1 l2 , ,cur
if(l1.val < l2.val):
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur.next.next = None
cur = cur.next
# l1 l2
if(l1 != None):
cur.next = l1
else:
cur.next = l2
return head.next
Java/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head= new ListNode(0);
ListNode cur = head;
// l1 l2 ,cur
while(l1 != null && l2 != null) {
if(l1.val < l2.val) {
cur.next = l1;
l1 = l1.next;
}
else {
cur.next = l2;
l2 = l2.next;
}
cur.next.next = null;// ,
cur = cur.next;
}
// l1 l2
if(l1 != null) cur.next = l1;
else cur.next = l2;
return head.next;
}
}