题目:合并两个有序链表
题目描述:
将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
public class MergeOrderedList {
public static void main(String[] args) {
Node node1 = new Node(1);
Node node2 = new Node(2);
Node node3 = new Node(4);
Node node4 = new Node(1);
Node node5 = new Node(3);
Node node6 = new Node(4);
node1.setNext(node2);
node2.setNext(node3);
node4.setNext(node5);
node5.setNext(node6);
Node newSort = merge(node1,node4);
System.out.println("合并后的排序是:");
while(newSort !=null){
System.out.print(newSort.getData()+" ");
newSort = newSort.getNext();
}
}
private static Node merge(Node node1, Node node2){
Node head = new Node(node1.data); //让第一个链表的节为头节点
Node temp = head; //将头结点赋给临时变量temp
node1 = node1.next; //node1指向下一个节点
while(true){ //循环
if (node1 == null && node2 == null){
break;
}else if(node1 == null){ //直接到另一个链表的当前表头
temp.next = node2;
break;
}else if (node2 == null){
temp .next = node1;
}else {
if (node1.data <= node2.data){ //选出较小的值作为新链表的头结点之后的下一节点
temp.next = new Node(node1.data);
temp = temp.next;
node1 = node1.next;
}else{
temp.next = new Node(node2.data);
temp = temp.next;
node2 = node2.next;
}
}
}
return head;
/*//判断合并的链表是否为空
if (node1 == null && node2 == null){
throw new RuntimeException("要合并的两条链表都为空");
}
//一条链表为空。直接返回另一条链表
if (node1 == null){
return node2;
}
if (node2 == null){
return node1;
}
//合并后的新链表的头结点
Node head = null;
//选出最小值作为合并后的新链表的头结点
if (node1.getData() <= node2.getData()){
head = node1;
//后移结点
node1 = node1.getNext();
}else{
head = node2;
//后移结点
node2 = node2.getNext();
}
//临时链表,用来链接合并链表的结点
Node temp = head;
while (node1 != null && node2 != null){
if (node1.getData() <= node2.getData() ){
temp.setNext(node1);
//后移结点
node1 = node1.getNext();
}else{
temp.setNext(node2);
//后移结点
node2 = node2.getNext();
}
//临时变量,用来链接合并链表的结点
temp = temp.getNext();
}
if (node1 == null){
temp.setNext(node2);
}
if (node2 == null){
temp.setNext(temp);
}
return head;*/
}
static class Node implements Serializable{
private int data;
private Node next;
public Node(int data) {
this.data = data;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
}