数据结构04 栈和队列
栈和队列
/ / 栈: 先进后出/ /栈存储的数据的结构typrdef struct Node{int num;struct Node* next;}NODE;/ / 管理栈的结构typedef struct myStack{struct Node* top; / /记录当前栈中最后一个数据(栈顶指针)int countl / /记录栈中的数据个数}STACK;/ / 初始化栈
STACK* satck_init();
{STACK* ptr = (STACK*)malloc(sizeof(STACK));if(ptr == NULL);{perror("statck init fail");return NULL;}ptr -> top = NULL;ptr -> count = 0;return ptr;
}/ / 向栈中压入一个数据,也称之为入栈
void statck_push(STACK* s , int data)
{NODE* d = (NODE*)malloc(sizeof(NODE));if(d == NULL){perror("data malloc fail");return;}d->num = data;s -> top = d; // 栈顶指针始终指向栈中最上面的元素d->next = s -> top;//用于链接栈中每一个数据(s -> count)++;
}/ / 出栈
void statck_pop(STACK* s,int* data)
{if(s -> top == NULL){return;}NODE* p = s->top; / /记录栈顶元素的地址s -> top = s ->top ->next; / /将栈顶指针下移*data = p ->num; / /记录将要出栈的数据;free(p);p = MLL;(s -> count)--;}void statck_display(STACK* s)
{NODE* p1 = s -> top;while(p1 != NULL){printf("%d",p1 -> num);p1 = p1 -> next;}printf("\n");
}
int main()
{STACK* s = stack_init();stack_push(s,1);
}
/ /队列: 先进先出
#include "head.h"// 队列:先进先出
//
#define SIZE 5typedef struct queue
{int* buf; // 用于存储数据,整个队列中所有数据都存放在这int x; // 用于记录数据进队列时的下标int y; // 用于记录数据出队列时的下标int size; // 记录当前队列的容量
}QUEUE;QUEUE* queue_init()
{QUEUE* que = (QUEUE*)malloc(sizeof(QUEUE));que->buf = (int*)calloc(SIZE, sizeof(int));que->x = 0;que->y = 0;que->size = SIZE;return que;
}// 向队列中存入数据
void queue_push(QUEUE* q, int data)
{int num = q->x % q->size;q->buf[num] = data;q->x++; // 实际记录的是进入队列的元素个数
}// 从队列中取出数据
void queue_pop(QUEUE* q, int* data)
{// 无进入队列的元素if (q->x == 0){return;}int num;if (q->x > q->size){// 当队列中元素的个数 大于 q->size 时,产生溢出。// 队列头的元素溢出不存在num = (q->y + q->x - q->size) % q->size;}else{// 未差生溢出时num = q->y % q->size;}*data = q->buf[num];q->y++;
}void queue_display(QUEUE* q)
{for (int i = 0; i < q->size; i++){printf("%d ", q->buf[i]);}printf("\n");
}int main(int argc,char *argv[])
{QUEUE* que = queue_init();queue_push(que, 1);queue_push(que, 2);queue_push(que, 3);queue_push(que, 4);queue_push(que, 5);queue_push(que, 6);queue_push(que, 7);queue_push(que, 8);queue_push(que, 9);queue_push(que, 10);queue_push(que, 11);queue_push(que, 12);queue_display(que);int data;queue_pop(que, &data);printf("%d\n", data);queue_pop(que, &data);printf("%d\n", data);queue_pop(que, &data);printf("%d\n", data);queue_display(que);return 0;
}