⬆︎
×

[LC] 0021 Merge Two Sorted Lists

Hyplus目录

Java

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;
    }
}
/**
 * <a href="https://leetcode.cn/problems/merge-two-sorted-lists/">Merge Two Sorted Lists</a>
 * 递归;链表
 */
class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null) {
            return list2;
        }
        if (list2 == null) {
            return list1;
        }

        ListNode head = new ListNode();
        ListNode p1 = list1, p2 = list2, p = head;
        while (p1 != null && p2 != null) {
            if (p1.val < p2.val) {
                p.next = p1;
                p1 = p1.next;
                p = p.next;
            } else {
                p.next = p2;
                p2 = p2.next;
                p = p.next;
            }
        }
        if (p1 != null) {
            p.next = p1;
        }
        if (p2 != null) {
            p.next = p2;
        }
        return head.next;
    }
}

Go

type ListNode struct {
    Val  int
    Next *ListNode
}

func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode {
    if list1 == nil {
        return list2
    }
    if list2 == nil {
        return list1
    }

    head := &ListNode{}
    p1 := list1
    p2 := list2
    p := head
    for p1 != nil && p2 != nil {
        if p1.Val < p2.Val {
            p.Next = p1
            p1 = p1.Next
            p = p.Next
        } else {
            p.Next = p2
            p2 = p2.Next
            p = p.Next
        }
    }
    for p1 != nil {
        p.Next = p1
        p1 = p1.Next
        p = p.Next
    }
    for p2 != nil {
        p.Next = p2
        p2 = p2.Next
        p = p.Next
    }
    return head.Next
}

发表评论