merge-two-smerge-two-sorted-listsorted-lists
2826 ワード
public class MergeSortListNode {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] A = {1,3,5,7,9,10,11};
int[] B = {2,4,6,8};
ListNode listNodeA = null , listNodeB = null;
if(A.length > 0){
listNodeA = new ListNode(A[0]);
}
ListNode l1 = listNodeA;
if(B.length > 0){
listNodeB = new ListNode(B[0]);
}
ListNode l2 = listNodeB;
for(int i = 1 ; i < A.length ; i++){
ListNode tmpListNode = new ListNode(A[i]);
listNodeA.next = tmpListNode;
listNodeA = listNodeA.next;
}
for(int i = 1 ; i < B.length ; i++){
ListNode tmpListNode = new ListNode(B[i]);
listNodeB.next = tmpListNode;
listNodeB = listNodeB.next;
}
ListNode res = mergeTwoLists(l1 , l2);
// while(l1 != null){
// System.out.println(l1.val);
// l1 = l1.next;
// }
// while(l2 != null){
// System.out.println(l2.val);
// l2 = l2.next;
// }
while(res != null){
System.out.println(res.val);
res = res.next;
}
}
public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode s1 , s2;
if(l1 == null && l2 != null){
return l2;
}else if(l1 != null && l2 == null){
return l1;
}else if(l1 == null && l2 == null){
return null;
}
// if(l1.val > l2.val){
// s1 = l2;
// s2 = l1;
// }else{
// s1 = l1;
// s2 = l2;
// }
s1 = l1;
s2 = l2;
ListNode tmpRes = s1;
ListNode res = null;
int startIndex = 0;
while(s1 != null && s2 != null){
if(s1.val < s2.val){
tmpRes = s1;
s1 = s1.next;
}else{
tmpRes = s2;
s2 = s2.next;
}
if(startIndex == 0){
res = tmpRes;
startIndex++;
}
System.out.println(tmpRes.val);
tmpRes = tmpRes.next;
}
while(res != null){
System.out.println(startIndex + " : " + res.val);
res = res.next;
}
if(s1 != null){
tmpRes = s1;
}
if(s2 != null){
tmpRes = s2;
}
// while(s2 != null){
// tmpRes.val = s2.val;
// System.out.println(tmpRes.val);
// tmpRes = tmpRes.next;
// s2 = s2.next;
// }
return res;
}
}