Created
October 31, 2012 15:49
-
-
Save jasdev/3987810 to your computer and use it in GitHub Desktop.
Create duplicates through recursion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Helping out a friend with a quick hack to make duplicates recursively (made in 2 mins) | |
import java.util.LinkedList; | |
public class Runner2 { | |
/** | |
* @param args | |
*/ | |
public static void main(String[] args) { | |
LinkedList l = new LinkedList<String>(); | |
l.add("A"); | |
l.add("B"); | |
l.add("A"); | |
l.add("B"); | |
makeDuplicates("B", l, 0); | |
System.out.print(l); | |
} | |
private static LinkedList<String> makeDuplicates(String target, LinkedList<String> l, int start) { | |
if(l.get(start).equals(target) && start != l.size() - 1){ | |
l.add(start + 1, target); | |
makeDuplicates(target, l, start + 2); | |
} | |
else if(l.get(start).equals(target) && start == l.size() - 1){ | |
l.add(start + 1, target); | |
return l; | |
} | |
else if(!l.get(start).equals(target) && start != l.size() - 1) | |
return makeDuplicates(target, l, start + 1); | |
else | |
return l; | |
return l; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment