You are given the heads of two sorted linked lists list1
and list2
.
Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
/**
* 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 {
private ListNode l3 = new ListNode();
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
if(isEmpty(list1)&&isEmpty(list2))
return null;
else if(isEmpty(list1)&&!isEmpty(list2))
return list2;
else if(!isEmpty(list1)&&isEmpty(list2))
return list1;
else {
int l1 = 0,i = 0;
while(!isEmpty(list1)&&!isEmpty(list2)){
if(i%2==0){
if(isGreat(list1.val,list2.val)){
merge(list1.val);
list1 = list1.next;
l1 = 1;
}else{
merge(list2.val);
list2 = list2.next;
l1 = 0;
}
}else
{
if(l1==1){
merge(list2.val);
list2 = list2.next;
l1 = 0;
}else
{
merge(list1.val);
list1 = list1.next;
}
}
if(isEmpty(list1)&&!isEmpty(list2)){
while(!isEmpty(list2)){
merge(list2.val);
list2 = list2.next;
}
}else if(!isEmpty(list1)&&isEmpty(list2)){
while(!isEmpty(list1)){
merge(list1.val);
list1 = list1.next;
}
}
}
}
return l3=l3.next;
}
public boolean isGreat(int a,int b){
return a<=b;
}
public void merge(int val){
ListNode newNode = new ListNode();
newNode.val = val;
newNode.next = null;
if(l3==null){
l3 = newNode;
}else
{
ListNode tmp = l3;
while(tmp.next!=null){
tmp = tmp.next;
}
tmp.next = newNode;
}
}
public boolean isEmpty(ListNode l){
return l==null;
}
}