第三次作業

JINPU發表於2024-04-27

include <stdio.h>

include <stdlib.h>

// 結構體定義
typedef struct {
int* data; // 整數資料
int size; // 資料長度
int index; // 當前索引
} NestedIterator;

// 主函式:扁平化巢狀列表
int* flatten(int** nestedList, int nestedListSize, int* nestedListColSize, int* returnSize) {
// 計算扁平化後的結果長度
int totalSize = 0;
for (int i = 0; i < nestedListSize; i++) {
totalSize += nestedListColSize[i];
}

// 分配記憶體空間
int* result = (int*)malloc(totalSize * sizeof(int));

// 使用棧來處理元素
int* stack = (int*)malloc(totalSize * sizeof(int));
int top = -1;

// 將所有列表元素壓入棧中
for (int i = nestedListSize - 1; i >= 0; i--) {
    for (int j = nestedListColSize[i] - 1; j >= 0; j--) {
        stack[++top] = nestedList[i][j];
    }
}

// 彈出棧頂元素並處理
int index = 0;
while (top >= 0) {
    int item = stack[top--];
    if (item >= 0) {
        result[index++] = item;  // 如果是整數,則新增到結果中
    } else {
        // 如果是列表,則將其元素逆序壓入棧中
        for (int i = nestedListColSize[-item - 1] - 1; i >= 0; i--) {
            stack[++top] = nestedList[-item - 1][i];
        }
    }
}

*returnSize = totalSize;
free(stack);

return result;

}

int main() {
int nestedList1[] = {1, 2, 3};
int nestedList2[] = {4, 5};
int nestedList3[] = {6};
int* nestedList[] = {nestedList1, nestedList2, nestedList3};
int nestedListSize = 3;
int nestedListColSize[] = {3, 2, 1};

int returnSize = 0;
int* flattenedList = flatten(nestedList, nestedListSize, nestedListColSize, &returnSize);

printf("Flattened List: ");
for (int i = 0; i < returnSize; i++) {
    printf("%d ", flattenedList[i]);
}
printf("\n");

free(flattenedList);

return 0;

}

相關文章