合并两个排序链表

来源:互联网 发布:steam游戏推荐软件 编辑:程序博客网 时间:2024/05/03 19:57

题目

将两个排序链表合并为一个新的排序链表
样例
给出 1->3->8->11->15->null,2->null, 返回 1->2->3->8->11->15->null。

解题

有序链表合并,找到较小的链接起来,指针后移

/** * 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 && l2==null)            return null;        if(l1==null)            return l2;        if(l2==null)            return l1;        ListNode p1 = l1;        ListNode p2 = l2;        ListNode mergeHead = new ListNode(-1);        ListNode p = mergeHead;        while(p1!=null && p2!=null){            if(p1.val <= p2.val){                p.next = p1;                p1 = p1.next;            }else{                p.next = p2;                p2 = p2.next;            }            p = p.next;        }        if(p1!=null){            p.next = p1;        }        if(p2!=null){            p.next = p2;        }        return mergeHead.next;    }}

递归方式

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 && l2==null)            return null;        if(l1==null)            return l2;        if(l2==null)            return l1;        ListNode p1 = l1;        ListNode p2 = l2;        ListNode mergeHead = null;        if(p1.val <= p2.val){            mergeHead = p1;            p1 = p1.next;        }else{            mergeHead = p2;            p2 = p2.next;        }        ListNode next = mergeTwoLists(p1,p2);        mergeHead.next = next;        return mergeHead;    }}
0 0