Leetcode 015--2つの秩序チェーンテーブルをマージ
2102 ワード
一、原題
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.
二、中国語
2つのソートチェーンテーブルを結合し、新しいリストを返します.新しいチェーンテーブルの結果は、元の2つのチェーンテーブルのノードから構成されます.つまり、マージできないチェーンテーブルには、新しく作成したノードが含まれません.
三、例を挙げる
1,3,5,7と2,4,6,8を合併すると12345678になります
四、考え方
2つのソートの良いチェーンテーブルなので、順番に挿入すればいいので、まず頭のノードを保存し、その後入り口が見つからないことに注意してください.
五、プログラム
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.
二、中国語
2つのソートチェーンテーブルを結合し、新しいリストを返します.新しいチェーンテーブルの結果は、元の2つのチェーンテーブルのノードから構成されます.つまり、マージできないチェーンテーブルには、新しく作成したノードが含まれません.
三、例を挙げる
1,3,5,7と2,4,6,8を合併すると12345678になります
四、考え方
2つのソートの良いチェーンテーブルなので、順番に挿入すればいいので、まず頭のノードを保存し、その後入り口が見つからないことに注意してください.
五、プログラム
package LeetCode;
class ListNodeMerge {
int val;
ListNodeMerge next;
ListNodeMerge() {}
ListNodeMerge(int x) {
val = x;
next = null;
}
}
public class Leetcode016 {
public static void main(String args[]){
ListNodeMerge n1 = new ListNodeMerge(1);
ListNodeMerge n2 = new ListNodeMerge(3);
ListNodeMerge n3 = new ListNodeMerge(5);
ListNodeMerge n4 = new ListNodeMerge(7);
n1.next = n2;
n2.next = n3;
n3.next = n4;
ListNodeMerge n1_1 = new ListNodeMerge(2);
ListNodeMerge n1_2 = new ListNodeMerge(4);
ListNodeMerge n1_3 = new ListNodeMerge(6);
ListNodeMerge n1_4 = new ListNodeMerge(8);
n1_1.next = n1_2;
n1_2.next = n1_3;
n1_3.next = n1_4;
ListNodeMerge list = new ListNodeMerge();
list = MergeTwoList(n1, n1_1);
while(list != null){
System.out.print(list.val+" ");
list = list.next;
}
}
/**
*
* @param n1
* @param n1_1
* @return
*/
public static ListNodeMerge MergeTwoList(ListNodeMerge n1, ListNodeMerge n2) {
//
ListNodeMerge head = new ListNodeMerge();
ListNodeMerge list3 = head;
while(n1 != null && n2 != null){
if(n1.val < n2.val){
list3.next = n1;
n1 = n1.next;
}else{
list3.next = n2;
n2 = n2.next;
}
list3 = list3.next;
}
if(n1==null)list3.next=n2;
else list3.next=n1;
return head.next;
}
}