用棧實現佇列

go__Ahead發表於2024-03-10

用棧實現佇列,需要兩個棧,一個定義為stackIn,另一個定義為stackOut
牛客NC76 用兩個棧實現佇列

1、佇列的push()操作

這個直接將資料壓入stcakIn,就行

void push(int node) {
	stackIn.push(node);
}

2、佇列的pop()操作

這裡有兩種解法

解法一:

當stcakOut為空時再將stackIn中的資料全部壓入stackOut,當stackOut不為空時,直接stackOut.pop()就行

int pop() {
// 只有當stOut為空的時候,再從stIn裡匯入資料(匯入stIn全部資料)
	if (stOut.empty()) {
// 從stIn匯入資料直到stIn為空
		while(!stIn.empty()) {
			stOut.push(stIn.top());
			stIn.pop();
		}
	}
	int result = stOut.top();
	stOut.pop();
	return result;
}

解法二:

每次出棧後直接將stack.Out資料全部壓回stack.In

int pop() {
//將第一個棧中內容彈出放入第二個棧中
	while (!stack1.empty()) {
		stack2.push(stack1.top());
		stack1.pop();
	}
//第二個棧棧頂就是最先進來的元素,即隊首
	int res = stack2.top();
	stack2.pop();
//再將第二個棧的元素放回第一個棧
	while (!stack2.empty()) {
		stack1.push(stack2.top());
		stack2.pop();
	}
	return res;
}

之所以這樣操作是因為佇列不是一次性全部輸入再全部輸出,也就是說pop()後會接push()也會接pop()。

完整程式碼:

class Solution {
    stack<int> stackIn;
    stack<int> stackOut;
  public:
    void push(int node) {
        stackIn.push(node);
    }

//解法一:
    int pop() {
        if (stackOut.empty()) {
            while (!stackIn.empty()) {
                stackOut.push(stackIn.top());
                stackIn.pop();
            }
        }
        int result = stackOut.top();
        stackOut.pop();
        return result;
    }

//解法二:
	int pop() {
        //將第一個棧中內容彈出放入第二個棧中
        while (!stack1.empty()) {
            stack2.push(stack1.top());
            stack1.pop();
        }
        //第二個棧棧頂就是最先進來的元素,即隊首
        int res = stack2.top();
        stack2.pop();
        //再將第二個棧的元素放回第一個棧
        while (!stack2.empty()) {
            stack1.push(stack2.top());
            stack2.pop();
        }
        return res;
    }

  private:
    stack<int> stack1;
    stack<int> stack2;
};

相關文章