Beispiel #1
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);
        }