Exemplo n.º 1
0
        public static ListNode Merge_Recursion(ListNode l1, ListNode l2)
        {
            if (l1 == null)
            {
                return(l2);
            }
            else if (l2 == null)
            {
                return(l1);
            }

            if (l1.val <= l2.val)
            {
                l1.next = Merge_Recursion(l1.next, l2);
                return(l1);
            }
            else
            {
                l2.next = Merge_Recursion(l1, l2.next);
                return(l2);
            }
        }
Exemplo n.º 2
0
        //without discarding first element
        //preparing node for the next iteration, that's why we need to check if next iteration is required
        public static ListNode AddTwoNumbers2(ListNode l1, ListNode l2)
        {
            if (l1 == null && l2 == null)
            {
                return(null);
            }

            ListNode curr  = new ListNode();
            ListNode head  = curr;
            int      carry = 0;

            while (l1 != null || l2 != null || carry > 0)
            {
                int sum = carry;
                if (l1 != null)
                {
                    sum = sum + l1.val;
                    l1  = l1.next;
                }
                if (l2 != null)
                {
                    sum = sum + l2.val;
                    l2  = l2.next;
                }

                carry    = sum / 10;
                curr.val = sum % 10;

                if (l1 != null || l2 != null || carry > 0) //atleast one more iteration remaining
                {
                    curr.next = new ListNode();
                    curr      = curr.next;
                }
            }
            return(head);
        }
Exemplo n.º 3
0
 public ListNode(int val = 0, ListNode next = null)
 {
     this.val  = val;
     this.next = next;
 }