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);
        }
        public Node FindIntersectionofTwoList(KarthicLinkedList list1, KarthicLinkedList list2)
        {
            //logic
            //since both the list are intersecting at a node. The length after the intersecting point will be the same
            //so calculate the height and then traverse the longer list to the difference
            //and the traverse both to find the common point

            int list1length = NodeHelper.GetLength(list1);
            int list2length = NodeHelper.GetLength(list2);

            KarthicLinkedList longer  = null;
            KarthicLinkedList shorter = null;

            if (list1length > list2length)
            {
                longer  = list1;
                shorter = list2;
            }
            else
            {
                longer  = list2;
                shorter = list1;
            }

            int difference = Math.Abs(list1length - list2length);

            //Traverse through the longer list for the difference

            Node node1 = longer.headnode;
            Node node2 = shorter.headnode;

            while (difference != 0)
            {
                node1 = node1.Next;
                difference--;
            }

            //here both will be at a same height now traverse to find the intersection point

            while (node1 != null && node2 != null & node1.Data != node2.Data)
            {
                node1 = node1.Next;
                node2 = node2.Next;
            }

            if (node1 == null || node2 == null)
            {
                return(null);
            }
            else
            {
                //both will be at the same node
                return(node1);
            }
        }