Learn-dsa..in 30 days!



























CC-11 : Merge stacks and remove duplicates.

Description:

Given 2 stacks, merge the 2 stacks after removing duplicates.

Test cases and expected outputs:

Input Parameters Expected outputs
Stack1
Stack nodes:
28<-21<-34<-17<-14<-9<-
Stack2
Stack nodes:
28<-14<-34<-23<-14<-8<-
Merged stacks, duplicates removed:
Stack nodes:
28<-21<-34<-17<-14<-9<-23<-8<-

Pseudocode:

Initialize a Deque based stack for holding the merged elements.
For each element in stack1:
Remove the top element from stack1.
If the current from stack1 is not present in merged elements stack, add the current from stack1 to merged elements stack.
For each element in stack2:
Remove the top element from stack2.
If the current from stack2 is not present in merged elements stack, add the current from stack2 to merged elements stack.
Return merged Deque stack.


Code:

public Deque< Integer > removeDuplicates(Deque< Integer > stack1,Deque< Integer > stack2) throws Exception{
	Deque< Integer > merged=new LinkedList< Integer >();
	int check;
	int s1Size=stack1.size();
	for (int idx=0; idx < s1Size; idx++) {
		
		check=stack1.pollFirst();
		if (merged.contains(check)==false) {
			merged.offerLast(check);	
		}
	}
    int s2Size=stack2.size();
	for (int idx=0; idx < s2Size; idx++) {
		check=stack2.pollFirst();
		if (merged.contains(check)==false) {
			merged.offerLast(check);	
		}	
	}	
	return merged;
}

Click here to download and run code and test cases !