题解 | #用两个栈实现队列#
用两个栈实现队列
https://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6
/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param node int整型 * @return 无 */ struct List { int data; struct List* next; }hand1={-1,NULL},hand2={-1,NULL};//头节点 typedef struct Stack { struct List* top; struct List* bottom; }Stack; static Stack S1 = { &hand1,NULL};//入队栈 static Stack S2 = { &hand2,NULL };//出队栈 void push(int node) { // write code here struct List* L; L = (struct List*)malloc(sizeof(struct List)); L->data=node; L->next=S1.top->next; S1.top->next=L; } /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param 无 * @return int整型 */ void move(){ while(S1.top->next!=NULL){ struct List* L; L = (struct List*)malloc(sizeof(struct List)); L->data=S1.top->next->data; L->next=S2.top->next; S2.top->next=L; L=S1.top->next->next; free(S1.top->next); S1.top->next=L; } } int pop() { // write code here int r; struct List* D; if(S2.top->next==NULL){ move(); } r=S2.top->next->data; D=S2.top->next->next; free(S2.top->next); S2.top->next=D; return r; }