package algorithm;
/*
Merge Two Sorted Lists(合并两个排好序的单链表)
原题
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
题目大意
合并两个排序链表并返回一个新的列表。新的链表的结果由原先的两个链表结点组成,也就是不能合并后的链表不能包含新创建的结点。
*/
public class MergeTowSortedLists {
public static class Node{
int value;
Node nextNode;
Node(int value){
this.value=value;
this.nextNode=null;
}
}
public static Node createNodeList(int[] tmp){
if(tmp==null){
return null;
}
Node node=null;
Node root=null;
for(int i=0;i<tmp.length;i++){
if(node==null){
node=new Node(tmp[i]);
root=node;
}else{
Node np=new Node(tmp[i]);
node.nextNode=np;
node=node.nextNode;
}
}
return root;
}
public static void printNode(Node node){
Node root=node;
if(node!=null){
do{
int value=root.value;
System.out.println(value);
root=root.nextNode;
}while(root!=null);
}
}
public static Node mergeTowSortedLists(Node node1,Node node2){
if(node1==null)
return node2;
if(node2==null)
return node1;
Node root=null;
Node tmp=null;
do{
int value1=node1.value;
int value2=node2.value;
if(value1<value2){//添加node1节点
if(root==null){//刚开始为空
root=node1;
tmp=node1;
node1=node1.nextNode;
}else{//添加node1
root.nextNode=node1;
root=node1;
node1=node1.nextNode;
}
}else{//添加node2节点
if(root==null){//刚开始为空
root=node2;
tmp=node2;
node2=node2.nextNode;
}else{
root.nextNode=node2;
root=node2;
node2=node2.nextNode;
}
}
}while(node1!=null&&node2!=null);
if(node1!=null){//添加node1
root.nextNode=node1;
}
if(node2!=null){//添加node1
root.nextNode=node2;
}
return tmp;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] tmp1={1,3,5,7,9,11};
int[] tmp2={2,4,6,8};
Node node1=createNodeList(tmp1);
Node node2=createNodeList(tmp2);
//printNode(node1);
//printNode(node2);
Node mergeNode=mergeTowSortedLists(node1,node2);
printNode(mergeNode);
}
}