BM42. 用两个栈实现队列
描述
示例1
输入:
["PSH1","PSH2","POP","POP"]
输出:
1,2
说明:
"PSH1":代表将1插入队列尾部 "PSH2":代表将2插入队列尾部 "POP“:代表删除一个元素,先进先出=>返回1 "POP“:代表删除一个元素,先进先出=>返回2示例2
输入:
["PSH2","POP","PSH1","POP"]
输出:
2,1
Go 解法, 执行用时: 2ms, 内存消耗: 1076KB, 提交时间: 2021-11-21
package main var stack1 []int var stack2 []int func Push(node int) { if stack1 == nil { stack1 = make([]int, 0) } stack1 = append(stack1, node) } func Pop() int { if len(stack1) == 0 { return 0 } tmp := stack1[0] stack1 = append(stack1[:0], stack1[1:]...) return tmp }
C 解法, 执行用时: 3ms, 内存消耗: 388KB, 提交时间: 2022-04-21
/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param node int整型 * @return 无 * * C语言声明定义全局变量请加上static,防止重复定义 */ static int instack[1000]; static int outstack[1000]; static int intop = 0; static int outtop = 0; void push(int node ) { // write code here *(instack + (intop++)) = node; } /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param 无 * @return int整型 */ int pop() { // write code here if (outtop == 0) { while (intop) { *(outstack + (outtop++)) = *(instack + (--intop)); } } return *(outstack + (--outtop)); }
C 解法, 执行用时: 3ms, 内存消耗: 396KB, 提交时间: 2022-05-23
/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param node int整型 * @return 无 * * C语言声明定义全局变量请加上static,防止重复定义 */ int s1[1000]; int WP=0; int RP=0; void push(int node ) { // write code here s1[WP++]=node; } /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param 无 * @return int整型 */ int pop() { // write code here return s1[RP++]; }
C 解法, 执行用时: 3ms, 内存消耗: 396KB, 提交时间: 2022-03-11
/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param node int整型 * @return 无 * * C语言声明定义全局变量请加上static,防止重复定义 */ static int instack[1000]; static int outstack[1000]; static int intop=0; static int outtop=0; void push(int node ) { // write code here *(instack + (intop++))=node; } /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param 无 * @return int整型 */ int pop() { // write code here if(outtop==0) { while(intop) { *(outstack + (outtop++))=*(instack + (--intop)); } } return *(outstack + (--outtop)); }
C 解法, 执行用时: 3ms, 内存消耗: 396KB, 提交时间: 2021-12-20
/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param node int整型 * @return 无 * * C语言声明定义全局变量请加上static,防止重复定义 */ static int stack_size = 1000; static int top_element = -1; static int end_element = 0; static int array[1000]; int is_full(void) { return (top_element == stack_size - 1); } int is_empty(void) { return (top_element == -1); } void push(int node ) { // write code here if (!is_full()) { top_element++; array[top_element] = node; } } /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param 无 * @return int整型 */ int pop() { // write code here int node ; if (! is_empty()) { node = array[end_element] ; end_element++; return node; } return -1; }