コード例 #1
0
        //This is recurrssive function
        //Note: Since we alredy did the padding, here both node1 and node2 will be of same length for sure
        public NodeAdditionResult AddTwoLinkedListNodesFromTail(Node node1, Node node2)
        {
            //stop the recurrsion at this condition
            if (node1 == null && node2 == null)
            {
                NodeAdditionResult emptynode = new NodeAdditionResult();
                return(emptynode);
            }
            //we have to do the addition from right to left so call the recurrsion first
            NodeAdditionResult runnerresult = new NodeAdditionResult();

            //Both the node is of same size..but during recursion stop the recursion when the next is null
            //so both node1 and node2 will be null at the same time
            runnerresult = AddTwoLinkedListNodesFromTail(node1 != null ? node1.Next : null, node2 != null ? node2.Next : null);

            int total = runnerresult.carry;

            if (node1 != null)
            {
                total = total + node1.Data;
            }
            if (node2 != null)
            {
                total = total + node2.Data;
            }

            //if the total is 12 add 2 to the node and add 1 to the carry
            //here resultnode will have the result of the right of the current node
            //append the resultnode with the result of the current node...it will be  current result --> right result
            runnerresult.resultnode = NodeHelper.AddNodeToFirst(runnerresult.resultnode, total % 10);
            runnerresult.carry      = total >= 10 ? 1 : 0;

            return(runnerresult);
        }
コード例 #2
0
        public Node AddTwoLinkedListFromBackwards(KarthicLinkedList list1, KarthicLinkedList list2)
        {
            int  length1 = NodeHelper.GetLength(list1);
            int  length2 = NodeHelper.GetLength(list2);
            Node result  = new Node();
            Node node1   = new Node();
            Node node2   = new Node();

            if (length1 > length2)
            {
                //Add padding to the shortest list
                node2 = NodeHelper.AddPadding(list2.headnode, (length1 - length2));
                node1 = list1.headnode;
            }
            else
            {
                node1 = NodeHelper.AddPadding(list1.headnode, (length2 - length1));
                node2 = list2.headnode;
            }

            //here the two nodes will be of same size
            NodeAdditionResult resultnode = AddTwoLinkedListNodesFromTail(node1, node2);

            //After adding two list, if there are any carry over add it on the top
            if (resultnode.carry > 0)
            {
                Node node = NodeHelper.AddNodeToFirst(resultnode.resultnode, resultnode.carry);
                return(node);
            }

            return(resultnode.resultnode);
        }