题目
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
举例:1 2 3 4 ;5 6 7 8
实现代码
package 牛客网;
public class Test {
public static class Merge {
public static ListNode Merge(ListNode list1,ListNode list2) {
if(list1 == null && list2 == null)
return null;
if(list1 == null)
return list2;
if(list2 == null)
return list1;
ListNode newNode = new ListNode(0);
ListNode tmp = new ListNode(0);
tmp = newNode;
if(list1.val < list2.val){
newNode.val = list1.val;
list1 = list1.next;
}
else{
newNode.val = list2.val;
list2 = list2.next;
}
while(list1!=null && list2!=null){
if(list1.val < list2.val){
newNode.next = list1;
newNode = newNode.next;
newNode.val = list1.val;
list1 = list1.next;
}else{
newNode.next = list2;
newNode = newNode.next;
newNode.val = list2.val;
list2 = list2.next;
}
}
if(list1!=null){
newNode.next = list1;
newNode = newNode.next;
//list1 = list1.next;
}
if(list2!=null){
newNode.next = list2;
newNode = newNode.next;
//list2 = list2.next;
}
return tmp;
}
public static void main(String[] args) {
ListNode list1 = new ListNode(1);
ListNode list2 = new ListNode(2);
list1.next = null;
list2.next = null;
ListNode head1 = list1;
ListNode head2 = list2;
for(int i = 2 ; i <=8 ; i ++){
if(i%2!=0)
{
ListNode temp = new ListNode(i);
temp.next = list1.next;
list1.next = temp;
list1 = temp;
}
}
for(int i = 4 ; i <=8 ; i ++){
if(i%2==0)
{
ListNode temp = new ListNode(i);
temp.next = list2.next;
list2.next = temp;
list2 = temp;
}
}
ListNode newNode = Merge(head1,head2);
for(int i = 1 ; i <= 8 ; i++){
System.err.println(newNode.val);
newNode = newNode.next;
}
}
}
}
ListNode类:
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}