1ms java clean code


  • 8
    P
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            if(l1!=null && l2==null) return l1;
            if(l2!=null && l1==null) return l2;
            ListNode head=new ListNode(0);
            ListNode node=head;
            while(l1!=null && l2!=null){
                if(l1.val>=l2.val) {
                    node.next=l2;
                    l2=l2.next;
                }
                else{
                    node.next=l1;
                    l1=l1.next;
                }
                node=node.next;
            }
            node.next = (l1 != null) ? l1 : l2;// Append the remaining elements in the longer list
            return head.next;
            /*head如果开始赋值null,则返回最后都是空,
            为了返回变化了的链表需要返回head.next,所以需要改变的是node.next
            ListNode head=null;
            ListNode node=head;
            while(l1!=null && l2!=null){
                if(l1.val>=l2.val) {
                    node=l2;
                    l2=l2.next;
                }
                else{
                    node=l1;
                    l1=l1.next;
                }
                node=node.next;
            }
            node = (l1 != null) ? l1 : l2;// Append the remaining elements in the longer list
            return head;
            */
        }
    }

  • 3
    G

    too much code, its un easy to understand


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.