链表四:合并两个排序的链表

/**
 * 题目:合并两个排序的链表
 * 描述:输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
 * 解决方案:
 * */

public class Four {
    //递归
    public static ListNode one(ListNode listOne,ListNode listTwo) {    
        if(listOne == null ) {
            return listTwo;
        }
        if(listTwo == null ) {
            return listOne;
        }
        ListNode head = null;
        if(listOne.var <listTwo.var) {
            head = listOne;
            head.next =one(listOne.next,listTwo);
        }else {
            head = listTwo;
            head.next = one(listOne,listTwo.next);
        }        
        return head;
    }

    //非递归
    public static ListNode two(ListNode listOne,ListNode listTwo) {    
        if(listOne == null ) {
            return null;
        }
        if(listTwo == null ) {
            return null;
        }
        ListNode temp = null;
        if(listOne.var < listTwo.var ) {
            temp =listOne;
            listOne = listOne.next;//将当前节点的后一个节点赋值给listOne
        }else {
            temp =listOne;
            listOne = listOne.next;
        }
        while(listOne!=null && listTwo != null) {
            if(listOne.var < listTwo.var) {
                temp.next = listOne;
                listOne = listOne.next;
            }else {
                temp.next = listTwo;
                listTwo = listTwo.next;
            }
        }
        return temp;
        
    }
    
    class ListNode{
        int var;
        ListNode next;
    }

}

 

posted @ 2018-11-16 14:57  弄潮儿儿  阅读(150)  评论(0编辑  收藏  举报