合併兩個有序鏈表C#

將兩個有序鏈表合併爲一個新的有序鏈表並返回。新鏈表是通過拼接給定的兩個鏈表的所有節點組成的。

示例:

輸入:1->2->4, 1->3->4
輸出:1->1->2->3->4->4

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/merge-two-sorted-lists
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int x) { val = x; }
 * }
 */
public class Solution
    {
        public ListNode MergeTwoLists(ListNode l1, ListNode l2)//相當於一個單鏈表
        {
            ListNode temp = new ListNode(0);
            ListNode l3=temp;//後面不能改動temp,只能從temp.next出發/
            while (l1 != null && l2 != null)
            {
                if (l1.val <= l2.val)
                {
                    temp.next = l1;
                    temp = temp.next;
                    l1 = l1.next;
                }
                else
                {
                    temp.next = l2;
                    temp = temp.next;
                    l2 = l2.next;
                }
            }
            if (l1 == null)
                temp.next = l2;
            else if (l2 == null)
                temp.next = l1;
            return l3.next;
        }
    }

注意理解單鏈表中結點的意義。
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章