21. Merge Two Sorted Lists

一、题目

  1、审题

    

  2、分析

    合并两个有序的链表元素组成一个新链表。

 

二、解答

  1、分析:

    方法一:

      依次比较两个链表中的元素,依次取数值小的元素插入新的链表。

  

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

        ListNode head = new ListNode(0);
        ListNode tempNode = head;
        
        while(l1 != null && l2 != null) {
            if(l1.val < l2.val) {
                tempNode.next = new ListNode(l1.val);
                l1 = l1.next;
            }
            else {
                tempNode.next = new ListNode(l2.val);
                l2 = l2.next;
            }
            tempNode = tempNode.next;
        }
        
        while(l1 != null) {
            tempNode.next = new ListNode(l1.val);
            tempNode = tempNode.next;
            l1 = l1.next;
        }
        while(l2 != null) {
            tempNode.next = new ListNode(l2.val);
            tempNode = tempNode.next;
            l2 = l2.next;
        }
        return head.next;
    }
}

 

    方法二:

      直接在两个链表之间进行比较,将值得大小插入第一个链表,最终返回第一个链表。

  

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

        ListNode head = new ListNode(0);
        ListNode cur = head;
        head.next = l1;

        while(l1 != null && l2 != null) {
            if(l1.val < l2.val) {
                l1 = l1.next;
            }
            else {      // l2 头结点插入  l1
                ListNode next = l2.next;
                l2.next = l1;
                cur.next = l2;
                l2 = next;
            }
            cur = cur.next;
        }

        if(l2 != null)
            cur.next = l2;
        return head.next;
    }
}

 

posted @ 2018-08-03 09:30  skillking2  阅读(90)  评论(0编辑  收藏  举报