学习计划算法: 第十天

87 阅读1分钟

合并两个有序链表

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

输入: l1 = [1,2,4], l2 = [1,3,4]
输出: [1,1,2,3,4,4]
输入: l1 = [], l2 = []
输出: []
输入: l1 = [], l2 = [0]
输出: [0]

leetcode-cn.com/problems/me…

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

        if(null == l1){
            return l2;
        }

        if(null == l2){
            return l1;
        }

        ListNode dummy = new ListNode();
        ListNode last = dummy;
        while(l1 != null && l2 != null){
            if(l1.val < l2.val){
                last.next = l1;
                last = l1;
                l1 = l1.next;
                continue;
            } 
            if(l1.val >= l2.val){
                last.next = l2;
                last = l2;
                l2 = l2.next;
            } 
        }

        while(l1 != null){
            last.next = l1;
            last = l1;
            l1 = l1.next;
        }

        while(l2 != null){
            last.next = l2;
            last = l2;
            l2 = l2.next;
        }

        return dummy.next;

    }
}

反转链表

输入: head = [1,2,3,4,5]
输出: [5,4,3,2,1]
输入: head = [1,2]
输出: [2,1]
输入: head = []
输出: []

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode dummy = new ListNode();
        while(head != null){
            ListNode temp = dummy.next;
            dummy.next = head;
            head = head.next;
            dummy.next.next = temp;
        }
        return dummy.next;
    }
}