大二,刚刚开始学数据结构与算法,写得不好。。。。
使用栈实现队列的下列操作:
1.init():初始化队列
2.push(x):将1个元素放入队列的尾部。
3.pop(): 从队列首部移除元素。
4.display():展示队列元素。
#include <stdlib.h> #include <stdio.h> typedef struct stack { int data; struct stack *next; } Stack; Stack *Init(int n) { Stack *top = NULL; int i; Stack *node; for (i = 1; i < n+1; i++) { node = (Stack *) malloc(sizeof(Stack)); node->data = i; node->next = top; top = node; printf("入队: %d\n",node->data); } return top; } void Display(Stack *top) { Stack *p = top; while (p->next != NULL) { printf("%d ", p->data); p = p->next; } printf("%d ", p->data); printf("\n"); } Stack *Push(Stack *top, int data) { Stack *node = (Stack *) malloc(sizeof(Stack)); node->data = data; node->next = top; top = node; printf("入队: %d\n",top->data); return top; } Stack *Pop(Stack *top) { Stack *p = top; printf("出队:%d\n",p->data); top = top->next; free(p); return top; } Stack * Queue(Stack *top,int data){ Stack *node = (Stack *) malloc(sizeof(Stack)); node->data = data; node->next = top; top = node; return top; } int main() { Stack *z1, *z2,*p; z1 = Init(10); z2 = Init(0); p=z1; while (p->next!=NULL){ z2=Queue(z2,p->data); p=p->next; } z2=Queue(z2,p->data); z2=Pop(z2); z2=Pop(z2); z2=Pop(z2); Display(z2); }