Ejemplo n.º 1
0
        public Node SumCaller(Node l1, Node l2)
        {
            int lenL1 = GetListLength(l1);
            int lenL2 = GetListLength(l2);

            if (lenL1 < lenL2)
            {
                l1 = PadLeft(l1, lenL2 - lenL1);
            }
            else
            {
                l2 = PadLeft(l2, lenL1 - lenL2);
            }

            SumNode sum = AddLists(l1, l2);

            if (sum.carry == 0)
            {
                return(sum.result);
            }
            else
            {
                sum.result = Prepend(sum.result, sum.carry);

                return(sum.result);
            }
        }
Ejemplo n.º 2
0
        public static SumNode SumOfLinkedListReverse(Node l1, Node l2, int carry)
        {
            if (l1 == null && l2 == null && carry == 0)
            {
                return(null);
            }

            SumNode resultNode = new SumNode();
            int     value      = 0;

            if (l1 != null)
            {
                value += l1.data;
            }
            if (l2 != null)
            {
                value += l2.data;
            }
            value += carry;

            resultNode.result = new Node(value);
            resultNode.sum    = value % 10;

            SumOfLinkedListReverse(l1 == null ? null : l1.next, l2 == null ? null : l2.next, value >= 10 ? 1 : 0);
            SumNode.resultList = LinkedList.Append(SumNode.resultList, resultNode.sum);

            resultNode.result = SumNode.resultList;
            return(resultNode);
        }
Ejemplo n.º 3
0
        public SumNode AddLists(Node l1, Node l2)
        {
            if (l1 == null && l2 == null)
            {
                return(new SumNode());
            }

            SumNode sum = AddLists(l1.next, l2.next);

            int value = l1.data + l2.data + sum.carry;

            sum.carry  = value / 10;
            sum.result = Prepend(sum.result, value % 10);

            return(sum);
        }