C solution for this issue


  • 0

    struct ZigzagIterator {
    int *v1;
    int *v2;
    int v1Size;
    int v2Size;
    int i;
    int j;
    int index;
    };

    struct ZigzagIterator zigzagIteratorCreate(int v1, int v1Size, int* v2, int v2Size) {
    struct ZigzagIterator Zig;
    Zig = (struct ZigzagIterator
    ) malloc(sizeof(struct ZigzagIterator));
    ~~![strikethrough text](![image url](image url))~~Zig->v1 = v1;
    Zig->v2 = v2;
    Zig->v1Size = v1Size;
    Zig->v2Size = v2Size;
    Zig->index = 0;
    Zig->i = 0;
    Zig->j = 0;
    return Zig;
    }

    bool zigzagIteratorHasNext(struct ZigzagIterator *iter) {
    if (iter->index < (iter->v1Size + iter->v2Size)) {
    return true;
    } else {
    return false;
    }
    }

    int zigzagIteratorNext(struct ZigzagIterator *iter) {
    int val = 0;
    if(iter->i < iter->v1Size && iter->j < iter->v2Size){
    if(iter->index%2 ==0){
    val = iter->v1[iter->i++];
    } else {
    val = iter->v2[iter->j++];
    }
    } else if(iter->i < iter->v1Size) {
    val = iter->v1[iter->i++];
    } else {
    val = iter->v2[iter->j++];
    }
    iter->index++;
    return val;
    }

    /** Deallocates memory previously allocated for the iterator */
    void zigzagIteratorFree(struct ZigzagIterator *iter) {
    free(iter);
    }

    /**

    • Your ZigzagIterator will be called like this:
    • struct ZigzagIterator *i = zigzagIteratorCreate(v1, v1Size, v2, v2Size);
    • while (zigzagIteratorHasNext(i)) printf("%d\n", zigzagIteratorNext(i));
    • zigzagIteratorFree(i);
      */[link text](link url)

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.