Java SE, very simple code with top 20% performance


  • 0
    D

    /**

    • 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) {

      ListNode prepare = new ListNode(0);
      ListNode correctCompass=prepare;
      prepare.next=l1;
      
      while(l1!=null && l2!=null)
      {
      	
      if(l1.val>l2.val)
      {
      	ListNode l3 = prepare.next;
      	prepare.next=l2;
      	l2=l2.next;
      	prepare.next.next=l3;		
      }
      else
      {
      	l1=l1.next;
      }
      
      prepare=prepare.next;
      	
      }
      if(l2!=null)
      {
      	prepare.next=l2;
      }
      return correctCompass.next;
      

      }
      }


Log in to reply
 

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