[LeetCode] Merge Two Sorted Lists

来源:互联网 发布:矩阵的一致性检验公式 编辑:程序博客网 时间:2024/05/21 10:20

Total Accepted: 12841 Total Submissions: 39914

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {        ListNode head1 = new ListNode(0);        ListNode head2 = new ListNode(0);        ListNode p1 = head1;        ListNode p2 = head2;                head1.next = l1;        head2.next = l2;                while (p1.next != null && p2.next != null) {            if (p1.next.val <= p2.next.val) p1 = p1.next;            else {                ListNode tmp = p2.next;                // delete tmp                p2.next = p2.next.next;                // insert tmp                tmp.next = p1.next;                p1.next = tmp;                p1 = p1.next;            }        }                if (p2.next != null) p1.next = p2.next;                return head1.next;    }}

 

// recursionpublic class Solution {    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {        if (l1 == null) return l2;        if (l2 == null) return l1;                ListNode head;                if (l1.val <= l2.val) {            head    = l1;            l1.next = mergeTwoLists(l1.next, l2);         } else {            head    = l2;            l2.next = mergeTwoLists(l1, l2.next);         }                return head;    }}


 

public class Solution {    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {        ListNode head = new ListNode(0);        ListNode node = head;                while (l1 != null && l2 != null) {            if (l1.val <= l2.val) {                node.next = l1;                l1 = l1.next;            } else {                node.next = l2;                l2 = l2.next;            }                        node = node.next;        }        if (l1 != null) node.next = l1;        if (l2 != null) node.next = l2;                return head.next;    }}



 

0 0
原创粉丝点击