iT邦幫忙

0

【LeetCode with C: A Series of Problem-Solving Techniques】-- Implement Queue using Stacks

  • 分享至 

  • xImage
  •  

Description

  1. Implement Queue using Stacks

Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty).

Implement the MyQueue class:

void push(int x) Pushes element x to the back of the queue.
int pop() Removes the element from the front of the queue and returns it.
int peek() Returns the element at the front of the queue.
boolean empty() Returns true if the queue is empty, false otherwise.
Notes:

You must use only standard operations of a stack, which means only push to top, peek/pop from top, size, and is empty operations are valid.
Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations.

Example 1:

Input
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
Output
[null, null, null, 1, 1, false]

Explanation
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false

Constraints:

1 <= x <= 9
At most 100 calls will be made to push, pop, peek, and empty.
All the calls to pop and peek are valid.

Follow-up: Can you implement the queue such that each operation is amortized O(1) time complexity? In other words, performing n operations will take overall O(n) time even if one of those operations may take longer.

Answer & Explaining

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

// 定義堆疊結構
typedef struct {
    int *data;//指標指向data陣列
    int top;
    int capacity;//最大容積
} Stack;

// 初始化堆疊
Stack* createStack(int capacity) {
    Stack* stack = (Stack*)malloc(sizeof(Stack));//動態分配記憶體給Stack
    stack->data = (int*)malloc(sizeof(int) * capacity);//動態分配記憶體給data陣列
    stack->top = -1;//初始stack為空
    stack->capacity = capacity;//設定容量
    return stack;
}

// 檢查堆疊是否為空
bool isEmpty(Stack* stack) {
    return stack->top == -1;
}

// 將元素Push 到Stack
void push(Stack* stack, int x) {
    if (stack->top == stack->capacity - 1) {
        printf("堆疊已滿\n"); // 錯誤處理,堆疊滿了
        return;//直接結束
    }
    stack->data[++stack->top] = x;//沒有滿則將top+1,並將x放入stack
}

// 從Stack Pop
int pop(Stack* stack) {
    if (isEmpty(stack)) {
        printf("堆疊已空\n"); // 錯誤處理,堆疊空了
        return -1; // 或其他錯誤值
    }
    return stack->data[stack->top--];//沒空的情況則取出top,並將top-1
}

// 查看堆疊頂部元素
int peek(Stack* stack) {
    if (isEmpty(stack)) {
        printf("堆疊已空\n"); // 錯誤處理,堆疊空了
        return -1;  // 或其他錯誤值
    }
    return stack->data[stack->top];//回傳頂端
}

// 釋放堆疊記憶體
void freeStack(Stack* stack) {
    free(stack->data);
    free(stack);
}



// 定義Queue結構
typedef struct {
    Stack* input;//用於push的stack
    Stack* output;//用於pop的stack
} MyQueue;

// 初始化Queue
MyQueue* myQueueCreate() {
    MyQueue* queue = (MyQueue*)malloc(sizeof(MyQueue));//動態分配記憶體
    queue->input = createStack(100); // 假設最多 100 個元素
    queue->output = createStack(100);
    return queue;
}

// 將元素 x push到Queue尾端
void myQueuePush(MyQueue* obj, int x) {
    push(obj->input, x);//將obj push到input stack
}

// 從Queue Top移除並返回元素
int myQueuePop(MyQueue* obj) {
    if(isEmpty(obj->output)) { // 若 output 堆疊為空,將 input Stack的元素轉移到 output Stack
        while(!isEmpty(obj->input)) {
            push(obj->output, pop(obj->input));
        }
    }
    return pop(obj->output);//pop出output stack的值
}

// 返回Queue的Top
int myQueuePeek(MyQueue* obj) {
     if(isEmpty(obj->output)) { // 若 output 堆疊為空,將 input Stack的元素轉移到 output stack
        while(!isEmpty(obj->input)) {
            push(obj->output, pop(obj->input));
        }
    }
    return peek(obj->output);
}

// 檢查Queue是否為空
bool myQueueEmpty(MyQueue* obj) {
    return isEmpty(obj->input) && isEmpty(obj->output);
}

// 釋放佇列記憶體
void myQueueFree(MyQueue* obj) {
    freeStack(obj->input);
    freeStack(obj->output);
    free(obj);
}

Testing

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

// 定義堆疊結構
typedef struct {
    int *data;//指標指向data陣列
    int top;
    int capacity;//最大容積
} Stack;

// 初始化堆疊
Stack* createStack(int capacity) {
    Stack* stack = (Stack*)malloc(sizeof(Stack));//動態分配記憶體給Stack
    stack->data = (int*)malloc(sizeof(int) * capacity);//動態分配記憶體給data陣列
    stack->top = -1;//初始stack為空
    stack->capacity = capacity;//設定容量
    return stack;
}

// 檢查堆疊是否為空
bool isEmpty(Stack* stack) {
    return stack->top == -1;
}

// 將元素Push 到Stack
void push(Stack* stack, int x) {
    if (stack->top == stack->capacity - 1) {
        printf("堆疊已滿\n"); // 錯誤處理,堆疊滿了
        return;//直接結束
    }
    stack->data[++stack->top] = x;//沒有滿則將top+1,並將x放入stack
}

// 從Stack Pop
int pop(Stack* stack) {
    if (isEmpty(stack)) {
        printf("堆疊已空\n"); // 錯誤處理,堆疊空了
        return -1; // 或其他錯誤值
    }
    return stack->data[stack->top--];//沒空的情況則取出top,並將top-1
}

// 查看堆疊頂部元素
int peek(Stack* stack) {
    if (isEmpty(stack)) {
        printf("堆疊已空\n"); // 錯誤處理,堆疊空了
        return -1;  // 或其他錯誤值
    }
    return stack->data[stack->top];//回傳頂端
}

// 釋放堆疊記憶體
void freeStack(Stack* stack) {
    free(stack->data);
    free(stack);
}



// 定義Queue結構
typedef struct {
    Stack* input;//用於push的stack
    Stack* output;//用於pop的stack
} MyQueue;

// 初始化Queue
MyQueue* myQueueCreate() {
    MyQueue* queue = (MyQueue*)malloc(sizeof(MyQueue));//動態分配記憶體
    queue->input = createStack(100); // 假設最多 100 個元素
    queue->output = createStack(100);
    return queue;
}

// 將元素 x push到Queue尾端
void myQueuePush(MyQueue* obj, int x) {
    push(obj->input, x);//將obj push到input stack
}

// 從Queue Top移除並返回元素
int myQueuePop(MyQueue* obj) {
    if(isEmpty(obj->output)) { // 若 output 堆疊為空,將 input Stack的元素轉移到 output Stack
        while(!isEmpty(obj->input)) {
            push(obj->output, pop(obj->input));
        }
    }
    return pop(obj->output);//pop出output stack的值
}

// 返回Queue的Top
int myQueuePeek(MyQueue* obj) {
     if(isEmpty(obj->output)) { // 若 output 堆疊為空,將 input Stack的元素轉移到 output stack
        while(!isEmpty(obj->input)) {
            push(obj->output, pop(obj->input));
        }
    }
    return peek(obj->output);
}

// 檢查Queue是否為空
bool myQueueEmpty(MyQueue* obj) {
    return isEmpty(obj->input) && isEmpty(obj->output);
}

// 釋放佇列記憶體
void myQueueFree(MyQueue* obj) {
    freeStack(obj->input);
    freeStack(obj->output);
    free(obj);
}

int main() {  // 主函數,程式從這裡開始執行
    MyQueue* myQueue = myQueueCreate();           // 建立一個佇列
    myQueuePush(myQueue, 1);                    // 推入 1
    myQueuePush(myQueue, 2);                    // 推入 2
    printf("Peek: %d\n", myQueuePeek(myQueue));    // 查看前端元素,輸出 1
    printf("Pop: %d\n", myQueuePop(myQueue));     // 彈出前端元素,輸出 1
    printf("Empty: %s\n", myQueueEmpty(myQueue) ? "true" : "false");  // 檢查是否為空,輸出 false
    myQueueFree(myQueue);                        // 釋放佇列記憶體
    return 0;                                   // 程式正常結束
}

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言