C语言--用队列实现栈

用队列实现栈

把数据从队头出来,再插入到队尾,最后一个不插入,直接出栈就实现了出栈操作。

取栈顶元素就是获取队尾元素。

其余操作入栈,判空,销毁类似于队列操作。

可以用一个队列实现栈,也可以用俩队列,我用的一个队列。

typedef int type;
typedef struct Node {
 type data;
 struct Node* next;
}Node;
typedef struct Queue {
 struct Node* front;
 struct Node* rear;
}Queue;
//队列初始化
void QueueInit(Queue* p) {
 p->front = p->rear = NULL;
}
//创建新节点
struct Node* CreatNode(type x) {
 Node* new = (Node*)malloc(sizeof(Node));
 new->data = x;
 new->next = NULL;
 return new;
}
//队列入队,尾插
void QueuePush(Queue* p, type x) {
 Node* node = CreatNode(x);
 if (p->front == NULL) {
  p->front = p->rear = node;
 }
 else {
  p->rear->next = node;
  p->rear = node;
 }
}
//队列出队,头删
void QueuePop(Queue* p) {
 if (p->front == NULL) {
  return;
 }
 Node* next = p->front->next;
 free(p->front);
 p->front = next;
 if (p->front == NULL) {
  p->rear = NULL;
 }
}
//获取队头元素
type QueueFront(Queue* p) {
 return p->front->data;
}
//获取队尾元素
type QueueRear(Queue* p) {
 return p->rear->data;
}
//获得队列的长度
int QueueSize(Queue* p) {
 int num = 1;
 Node* cur = p->front;
 while (cur) {
  num++;
  cur = cur->next;
 }
 return num;
}
//判断队列是否为空
int QueueEmpty(Queue* p) {
 if (p->front == NULL) {
  return 1;
 }
 return 0;
}
//队列销毁
void QueueDes(Queue* p) {
 Node* cur = p->front;
 while (cur) {
  cur->data = NULL;
  cur->next = NULL;
  free(cur);
  cur = cur->next;
 }
 p->front = NULL;
 p->rear = NULL;
}
//用一个队列实现栈的功能
typedef struct {
 Queue q;
} MyStack;
//栈初始化
MyStack* myStackCreate() {
 MyStack* ms = (MyStack*)malloc(sizeof(MyStack));
 QueueInit(&ms->q);
 return ms;
}
//入栈
void myStackPush(MyStack* obj, int x) {
 QueuePush(&obj->q, x);
}
//出栈
int myStackPop(MyStack* obj) {
 int ret = 0;
 int size = QueueSize(&obj->q);
 while (size > 1) {
  //从队列头出来,再从尾入
  int front = QueueFront(&obj->q);
  QueuePop(&obj->q);
  QueuePush(&obj->q, front);
  --size;
 }
 //最后一个直接出队列,相当于栈顶元素出栈
 ret = QueueFront(&obj->q);
 QueuePop(&obj->q);
 return ret;
}
//取栈顶元素
int myStackTop(MyStack* obj) {
 return QueueRear(&obj->q);
}
//判空
bool myStackEmpty(MyStack* obj) {
 return QueueEmpty(&obj->q);
}
//释放空间
void myStackFree(MyStack* obj) {
 QueueDes(&obj->q);
 free(obj);
}

你可能感兴趣的:(数据结构)