剑指offer14--将两个有序链表合并

题目:输入两个递增排序的链表,合并这两个链表并使新链表中的结点仍然是按照递增排序的

两个有序链表的排序还是比较简单的,重要的是要考虑一些情况

package 剑指offer;
/*题目:输入两个递增排序的链表,合并这两个链表并使新链表中的结点仍然是按照递增排序的*/
public class Test17 {
	public static void main(String args[]){
		LinkList head1 = new LinkList();
        head1.value = 1;

        head1.next = new LinkList();
        head1.next.value = 3;

        head1.next.next = new LinkList();
        head1.next.next.value = 5;

        head1.next.next.next = new LinkList();
        head1.next.next.next.value = 7;

        head1.next.next.next.next = new LinkList();
        head1.next.next.next.next.value = 9;
        
        
		LinkList head2 = new LinkList();
        head2.value = 2;

        head2.next = new LinkList();
        head2.next.value = 4;

        head2.next.next = new LinkList();
        head2.next.next.value = 6;

        head2.next.next.next = new LinkList();
        head2.next.next.next.value = 8;

        head2.next.next.next.next = new LinkList();
        head2.next.next.next.next.value = 10;
        
        
        LinkList list = merageTwoOrderList(head1, head2);
        while(list != null){
        	System.out.print(list.value+"  ");
        	list = list.next;
        }
	}
	
	public static class LinkList{
		int value;
		LinkList next;
	}
	
	public static LinkList merageTwoOrderList(LinkList head1, LinkList head2){
        if (head1 == null) {
            return head2;
        }

        if (head2 == null) {
            return head1;
        }
		
		LinkList root = new LinkList();
		LinkList pointer = root;
		while((head1 != null) && (head2 != null)){
			// 当两个元素都存在时才可以比较,所以关系符使用&&
			if(head1.value < head2.value){
				pointer.next = head1;
				head1 = head1.next;
			}else{
				pointer.next = head2;
				head2 = head2.next;
			}
			pointer = pointer.next;
		}
		// 当一个链表已经完了,另一个链表中还有元素的情况
		if(head1 != null){
			pointer.next = head1;
		}
		if(head2 != null){
			pointer.next = head2;
		}
		return root.next;
	}
	
}

我不是菜鸟,是被菜鸟吃的小虫子

你可能感兴趣的:(剑指offer14--将两个有序链表合并)