leetcode做题总结,题目Merge Two Sorted Lists 2012/03/30

来源:互联网 发布:免费喊单软件 编辑:程序博客网 时间:2024/06/06 09:08

两有序链表归并,归并排序即可。


public ListNode mergeTwoLists(ListNode l1, ListNode l2) {        ListNode l3 = new ListNode(0);        ListNode st = l3;        while(l1!=null&&l2!=null){            if(l1.val>l2.val){                l3.next = new ListNode(l2.val);                l2=l2.next;                l3=l3.next;            }else{                l3.next = new ListNode(l1.val);                l1=l1.next;                l3=l3.next;            }        }        while(l1!=null){            l3.next = new ListNode(l1.val);            l1=l1.next;            l3=l3.next;        }        while(l2!=null){            l3.next = new ListNode(l2.val);            l2=l2.next;            l3=l3.next;        }        return st.next;    }

Update 2015/08/20: 上面的答案有两个缺陷,第一是没有必要定义一个0节点,可以直接使用引用,二是在其中一个链为空之后没有必要再使用while,可以直接使用if连接即可

/** * Definition for ListNode. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int val) { *         this.val = val; *         this.next = null; *     } * } */ public class Solution {    /**     * @param ListNode l1 is the head of the linked list     * @param ListNode l2 is the head of the linked list     * @return: ListNode head of linked list     */    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {        // write your code here        if (l1 == null)            return l2;        if (l2 == null)            return l1;        ListNode head;        if (l1.val <= l2.val){            head = l1;            l1 = l1.next;        } else {            head = l2;            l2 = l2.next;        }        ListNode start = head;        while (l1 != null && l2 != null){            if (l1.val <= l2.val){                head.next = l1;                l1 = l1.next;            } else {                head.next = l2;                l2 = l2.next;            }            head = head.next;        }        if (l1 != null){            head.next = l1;        }        if (l2 != null){            head.next = l2;        }        return start;    }}


0 0
原创粉丝点击