Created
April 22, 2014 06:35
-
-
Save seanzhu/11167427 to your computer and use it in GitHub Desktop.
Flatten a nested list. Java version.
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
package practice; | |
import java.util.LinkedList; | |
import java.util.List; | |
import static java.util.Arrays.asList; | |
public class NestList { | |
public static List<Integer> flatten(List<?> list) { | |
List<Integer> ret = new LinkedList<Integer>(); | |
flattenHelper(list, ret); | |
return ret; | |
} | |
public static void flattenHelper(List<?> nestedList, List<Integer> flatList) { | |
for (Object item : nestedList) { | |
if (item instanceof List<?>) { | |
flattenHelper((List<?>) item, flatList); | |
} else { | |
flatList.add((Integer) item); | |
} | |
} | |
} | |
public static void main(String[] args) { | |
List<Object> nestedList = lst(1, lst(2, lst(3, 4)), lst(5, 6, 7), 8, lst(lst(9, 10))); | |
List<Integer> flatList = flatten(nestedList); | |
System.out.println(nestedList); | |
System.out.println(flatList); | |
} | |
private static List<Object> lst(Object... objs) { | |
return asList(objs); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment