Home » C++ » [leetcode281]Zigzag Ite

Question:

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

For, example, given, two, 1D, vectors:

v1 = [1, 2]

v2 = [3, 4, 5, 6]

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

Follow, up:, What, if, are, given, K, 1D, vectors, How, well, can, your, code,, be, extended, to, such, you, cases,

Clarification for the follow up question Update (2015-09-18): 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",
Given the following input:

[1,2,3]

[4,5,6,7]

[8,9]

It, should, return, [1,4,8,2,5,9,3,6,7].

analysis:

implements an iterator that cross accesses two arrays.

very simple, first access V1, to determine whether V1 still have data, if the data is output, or directly output V2, all the remaining elements.

access V2 again, the same judge whether V2 still have data, if there is data output, or directly output V1 all remaining data.

cross.

in turn

The

code is as follows:

`class, ZigzagIterator {Public:ZigzagIterator (vector&, V1, vector&, V2) {Bs[0] = v1.begin (), bs[1] = v2.begin ();Es[0] = v1.end (), es[1] = v2.end ();P = 0;}Int, next () {Int elem;If (bs[0] = es[0])Elem = *bs[1]++;ElseIf (bs[1] = es[1])Elem = *bs[0]++;{elseElem = *bs[p]++;P = (P + 1)% 2;}Return elem;}Bool, hasNext () {Return bs[0]! = es[0] bs[1] = es[1] ||;}Private:Int p;Vector:: iterator, bs[2], es[2];};`