题目 :输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
思想 :类似于排有序数组,,,定义新node/数组.每次遍历将小的放在node/数组中,移动小的node/数组的游标
package com.algorithm.offer;
import com.sun.xml.internal.bind.v2.model.core.ID;
public class Merge {
static class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
//输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
public static ListNode Merge(ListNode list1,ListNode list2) {
if (list1==null){
return list2;
}
if (list2==null){
return list1;
}
ListNode mergeHead =null;
ListNode curr=null;
while (list1!=null&&list2!=null){
if (list1.val<=list2.val){
if(mergeHead == null){
mergeHead = curr = list1;
}else{
curr.next = list1;
curr = curr.next;
}
list1 = list1.next;
}else {
if(mergeHead == null){
mergeHead = curr = list2;
}else{
curr.next = list2;
curr = curr.next;
}
list2 = list2.next;
}
}
if (list1!=null){
curr.next=list1;
}else {
curr.next=list2;
}
return mergeHead;
}
public static void main(String[] args){
ListNode l1=new ListNode(1);
ListNode l2=new ListNode(3);
ListNode l3=new ListNode(4);
ListNode l6=new ListNode(5);
l1.next=l2;
l2.next=l3;
l3.next=l6;
ListNode l4=new ListNode(2);
ListNode l5=new ListNode(3);
ListNode l8=new ListNode(3);
l4.next=l5;
l5.next=l8;
ListNode node = Merge(l1, l4);
while (node!=null){
System.out.print(node.val+" ");
node=node.next;
}
}
}