281 Zigzag Iterator

Zigzag Iterator

https://yeqiuquan.blogspot.com/2017/06/281-zigzag-iterator.html



The Java.util.LinkedList.remove() method is used to remove an element from a linked list. The element is removed from the beginning or head of the linked list.

Syntax:
LinkedList.remove()
Parameters: This function does not take any parameter.


// my version . Passed 

public class ZigzagIterator {
    Queue<Iterator> queue = new LinkedList<>();

    public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
        // Queue<Iterator> queue = new LinkedList<>();
        // queue needs to be placed under class, so other public 
        // classes can also access to it 
        
        if(v1.iterator().hasNext()){
            queue.offer(v1.iterator()); // iterator() , not iterator 
        }
        if(v2.iterator().hasNext()){
            queue.offer(v2.iterator());
        }
        
    }

    public int next() {
        Iterator<Integer> current = queue.poll();
        int curNum = current.next(); // current.next() is an object 
        if(current.hasNext()){
            queue.offer(current);
        }
        return curNum;
        
    }

    public boolean hasNext() {
        return !queue.isEmpty();
        
    }
}

 

Given two 1d vectors, implement an iterator to return their elements alternately.

Example:

Input:
v1 = [1,2]
v2 = [3,4,5,6] 

Output: [1,3,2,4,5,6]

Explanation: By calling next repeatedly until hasNext returns false, 
             the order of elements returned by next should be: [1,3,2,4,5,6].

Follow up: What if you are given k 1d vectors? How well can your code be extended to such cases?

Clarification for the follow up question:
The "Zigzag" order is not clearly defined and is ambiguous for k > 2 cases. If "Zigzag" does not look right to you, replace "Zigzag" with "Cyclic". For example:

Input:
[1,2,3]
[4,5,6,7]
[8,9]

Output: [1,4,8,2,5,9,3,6,7].

 

posted on 2018-08-10 16:31  猪猪&#128055;  阅读(82)  评论(0)    收藏  举报

导航