标签:
这个题目的意思是实现一个迭代器。网上有一个方法是这样实现的。
public class NestedIterator implements Iterator<Integer> {
int index = 0;
List<Integer> vals;
public NestedIterator(List<NestedInteger> nestedList) {
vals = parser(nestedList);
}
public List<Integer> parser(List<NestedInteger> nestedList) {
List<Integer> res = new ArrayList<Integer>();
for (NestedInteger n : nestedList) {
if (n.isInteger()) {
res.add(n.getInteger());
} else {
res.addAll(parser(n.getList()));
}
}
return res;
}
public Integer next() {
if (index < vals.size()) {
int val = vals.get(index);
index++;
return val;
} else {
return -1;
}
}
public boolean hasNext() {
return !(index >= vals.size());
}
}
这种方法简单粗暴。但是并不是理想的实现方式,因为这样的实现导致内存使用要提高一倍。我自己的实现方式是这样的
import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
interface NestedInteger {
// @return true if this NestedInteger holds a single integer, rather than a nested list.
public boolean isInteger();
// @return the single integer that this NestedInteger holds, if it holds a single integer
// Return null if this NestedInteger holds a nested list
public Integer getInteger();
// @return the nested list that this NestedInteger holds, if it holds a nested list
// Return null if this NestedInteger holds a single integer
public List<NestedInteger> getList();
}
public class NestedIterator implements Iterator<Integer> {
static Deque<List<NestedInteger>> stack=new LinkedList<List<NestedInteger>>();
static Deque<Integer> stackIndex=new LinkedList<Integer>();
List<NestedInteger> nestedList;
public NestedIterator(List<NestedInteger> nestedList) {
stack.add(nestedList);
stackIndex.add(0);
}
@Override
public Integer next() {
int currIndex=stackIndex.pollLast();
List<NestedInteger> currList=stack.peekLast();
NestedInteger currEle=currList.get(currIndex);
if(!currEle.isInteger())
{
stack.addLast(currEle.getList());
stackIndex.addLast(0);
return next();
}
int result=currEle.getInteger();
if(currIndex+1>=currList.size())
{
stack.pollLast();
}
else
{
stackIndex.addLast(currIndex+1);
}
return result;
}
@Override
public boolean hasNext() {
if(stack.size()==0)
{
return false;
}
else
{
int currIndex=stackIndex.peekLast();
List<NestedInteger> currList=stack.peekLast();
if(!currList.get(currIndex).isInteger()&&currList.get(currIndex).getList()==null)
{
stack.pollLast();
if(currIndex+1>=currList.size())
{
stackIndex.pollLast();
}
else
{
stackIndex.pollLast();
stackIndex.addLast(currIndex+1);
}
return hasNext();
}
}
return true;
}
}
/**
* Your NestedIterator object will be instantiated and called as such:
* NestedIterator i = new NestedIterator(nestedList);
* while (i.hasNext()) v[f()] = i.next();
*/
不过。这个算法不能处理[1,2,3,[]]这种情况,可能是我没有弄懂[]在oj里面的表示方式。不过只要没有[]这种情况,代码运行正常
标签:
原文地址:http://blog.csdn.net/bleuesprit/article/details/51348449