Created
March 7, 2019 09:50
-
-
Save liuqinh2s/e42dd5a2f59d3d916651d8a88fc58ee6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution { | |
public ListNode Merge(ListNode list1,ListNode list2) { | |
if(list1==null){ | |
return list2; | |
} | |
if(list2==null){ | |
return list1; | |
} | |
ListNode node = new ListNode(0); | |
ListNode head = node; | |
while(list1!=null && list2!=null){ | |
if(list1.val<list2.val){ | |
node.next = list1; | |
list1 = list1.next; | |
}else{ | |
node.next = list2; | |
list2 = list2.next; | |
} | |
node = node.next; | |
} | |
if(list1!=null){ | |
node.next = list1; | |
} | |
if(list2!=null){ | |
node.next = list2; | |
} | |
return head.next; | |
} | |
private void printList(ListNode head){ | |
while(head!=null){ | |
System.out.print(head.val+" "); | |
head = head.next; | |
} | |
System.out.println(); | |
} | |
public static void main(String[] args) { | |
Solution solution = new Solution(); | |
int[] array1 = {1, 7, 10, 30}; | |
int[] array2 = {3, 4, 5, 9, 20, 40}; | |
ListNode list1 = new ListNode(0); | |
ListNode head1 = list1; | |
ListNode list2 = new ListNode(0); | |
ListNode head2 = list2; | |
for(int i=0;i<array1.length;i++){ | |
list1.next = new ListNode(array1[i]); | |
list1 = list1.next; | |
} | |
for(int i=0;i<array2.length;i++){ | |
list2.next = new ListNode(array2[i]); | |
list2 = list2.next; | |
} | |
solution.printList(head1.next); | |
solution.printList(head2.next); | |
solution.printList(solution.Merge(head1.next, head2.next)); | |
} | |
} | |
class ListNode{ | |
int val; | |
ListNode next; | |
ListNode(int k){ | |
val = k; | |
next=null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment