题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
listNode.java
public class ListNode {
int val;
ListNode next=null;
ListNode(int val){
this.val=val;
}
}
LinkList.java
public class LinkList {
public ListNode first;
private int pos=0;
public LinkList(){
this.first=null;
}
public void addFirstNode(int data){
ListNode node=new ListNode(data);
node.next=first;
first=node;
}
public void print(){
ListNode mynode=this.first;
while(mynode!=null){
System.out.print(mynode.val+" ");
mynode=mynode.next;
}
System.out.println();
}
public ListNode getFirstNode(){
return this.first;
}
}
Solution.java
package mergeTwoList;
/**
* Created by Administrator on 2017/3/16.
*/
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
ListNode mylist=null;
ListNode fistNode=null;
if(list1==null){
return list2;
}
if(list2==null){
return list1;
}
while((list1!=null)&&(list2!=null)){
if(list1.val<=list2.val){
if(fistNode==null) {
mylist=fistNode=new ListNode(list1.val);
list1=list1.next;
}else{
mylist.next=new ListNode(list1.val);
list1=list1.next;
mylist=mylist.next;}
}else{
if(fistNode==null){
mylist=fistNode=new ListNode(list2.val);
list2=list2.next;
}else{
mylist.next=new ListNode(list2.val);
list2=list2.next;
mylist=mylist.next;
}
}
}
if(list1==null){
mylist.next=list2;
}else{
mylist.next=list1;
}
return fistNode;
}
}
test.java
package mergeTwoList;
import java.util.LinkedList;
/**
* Created by Administrator on 2017/3/16.
*/
public class test{
public static void main(String[] args){
Solution myso=new Solution();
LinkList mylist_one=new LinkList();
mylist_one.addFirstNode(8);
mylist_one.addFirstNode(6);
mylist_one.addFirstNode(3);
mylist_one.addFirstNode(1);
LinkList mylist_two=new LinkList();
mylist_two.addFirstNode(13);
mylist_two.addFirstNode(10);
mylist_two.addFirstNode(8);
mylist_two.addFirstNode(5);
mylist_two.addFirstNode(3);
mylist_two.addFirstNode(1);
ListNode mylist_thrid_first=null;
mylist_thrid_first=myso.Merge(mylist_one.getFirstNode(),mylist_two.getFirstNode());
while(mylist_thrid_first!=null){
System.out.print(mylist_thrid_first.val+" " );
mylist_thrid_first=mylist_thrid_first.next;
}
}
}
这一种方法比较好想。
=============华丽的分隔线===============
还有一种递归的方法。
public ListNode Merge(ListNode list1,ListNode list2){
if(list1==null){
return list2;
}
if(list2==null){
return list1;
}
if(list1.val<=list2.val){
list1.next=Merge(list1.next,list2);
return list1;
}else{
list2.next=Merge(list1,list2.next);
return list2;
}
}