30. Multiply two linked list

30. Multiply two linked list


Problem link :- click here


package Linked_List;

public class LinkedList__30
{

	static long multiplyLinkedLists(Node h1, Node h2)
	{
		//Lets generate the number from the linked list
		int n1 = 0;
		while(h1 != null)
		{
			n1 = n1*10   +  h1.data;
			h1 = h1.next;
		}
		
		int n2 = 0;
		while(h2 != null)
		{
			n2 = n2*10   +  h2.data;
			h2 = h2.next;
		}
		
		return n1 * n2;
	}
	
	public static void main(String[] args)
	{
		LinkedList list1 = new  LinkedList();
		list1.push(9);
		list1.push(6);
		list1.push(4);
		
		LinkedList list2 = new  LinkedList();
		list2.push(8);
		list2.push(4);
		
		System.out.println("Linked lists : ");
		printList(list1);
		printList(list2);
		long ans = multiplyLinkedLists(list1.head, list2.head);
		System.out.println("\nProduct : " + ans);
	}

	static void printList(LinkedList list)
	{
		for(Node temp=list.head; temp!=null; temp=temp.next)
			System.out.print(temp.data + "-> ");
		System.out.println("null");
	}
}

Time complexity :- O(n)
Space complexity :- O(1)

Comments

Popular posts from this blog

4.Sort an array of 0's, 1's & 2's.

1. Reverse

3. Height of Binary tree