在标准规定里,栈是一种特殊的线性表,有栈底和栈顶两端,规定它只能从栈顶出入数据,所以这也是栈的一个基本原则:先入栈的后出栈(后入栈先出栈)。我们在实现一个栈时,通常使用顺序表来实现,以顺序表的表尾来做栈顶。

例如上面的一个栈,栈底的位置一直不改变,从栈顶进一个数据(指向栈顶的指针加一),然后又从栈顶出一个数据(指向栈顶的指针减一)。
- typedef int Stack_data_type;
- #define Maxca 10
-
- typedef struct Stack
- {
- Stack_data_type * St;
- int top;
- int capacity;
- }stack;
-
-
- //栈初始化
- void Stack_init(stack* ps)
- {
- ps->capacity = Maxca;
- ps->top = 0;
- ps->St = (Stack_data_type*)malloc(ps->capacity * sizeof(Stack_data_type));
- }
在栈的初始化时,top指针初始值设置为0,每次添加数据后,top++,所以top一直指向着栈内最后一个数据的下一个数据节点。(图解如下)

- //入栈
- void Stack_push(stack* ps, Stack_data_type x)
- {
- ps->St[ps->top] = x;
- ps->top++;
- if (ps->top == ps->capacity)
- {
- Stack_data_type* ptr = (Stack_data_type*)realloc(ps->St, ps->capacity * 2 * sizeof(Stack_data_type));
- if (ptr == NULL)
- {
- perror(realloc);
- }
- else
- {
- ps->St = ptr;
- ps->capacity *= 2;
- }
- }
- }
-
- //出栈
- Stack_data_type Stack_pop(stack* ps)
- {
- if (ps->top == 0)
- {
- printf("栈已经清空\n");
- exit(-1);
- }
- else
- {
- ps->top--;
- printf("出栈%d \n", ps->St[ps->top]);
- return ps->St[ps->top];
- }
- }
这里需要注意的是,当栈慢的时候需要自动开辟新的空间。还有在对栈进行出栈操作时,要判断top是否为0,当top为0时,代表栈已经清空了。
队列:基本概念,该结构只能从一端入数据,另一端出数据。所以这也是队列的特殊属性,先入队列的数据先出队列,后入队列的数据后出队列。(先进先出,后进后出)

在实现这种结构时,一般推荐使用单链表。定义两个指针去维护这个单链表,一个指向表头,一个指向表尾。有数据入队列时就尾插,出数据就头删。并且将指向头位置的指针向后移动一位。
- #define _CRT_SECURE_NO_WARNINGS 1
- #include"Queue.h"
-
- //初始化
- void Queue_init(que* ps)
- {
- ps->head = ps->tail = NULL;
- }
-
- //入队
- void Queue_push(que* ps, Queue_data_type x)
- {
- assert(ps);
- Queue* newnode = (Queue*)malloc(sizeof(Queue));
- newnode->data = x;
- newnode->next = NULL;
- if (ps->head == NULL)
- {//说明此时还没有节点
- ps->head = ps->tail = newnode;
- }
- else
- {
- ps->tail->next = newnode;
- ps->tail = newnode;
- }
- }
-
- //出队
- Queue_data_type Queue_pop(que* ps)
- {
- assert(ps);
- assert(ps->head);
- Queue_data_type tmp =0;
- Queue* cur = NULL;
- if (ps->head->next == NULL)
- {
- tmp = ps->head->data;
- free(ps->head);
- return tmp;
- }
- else
- {
- tmp = ps->head->data;
- cur = ps->head->next;
- free(ps->head);
- ps->head =cur;
- return tmp;
- }
- }
-
- //打印栈
- void Queue_Prin(que* ps)
- {
- Queue* cur = ps->head;
- assert(ps && ps->head);
- while (cur)
- {
- printf("%d ", cur->data);
- cur = cur->next;
- }
- printf("\n");
- }
-
- //释放队列
- void Queue_release(que* ps)
- {
- assert(ps && ps->head);
- Queue* cur = ps->head;
- Queue* next = cur->next;
- while (cur->next)
- {
- free(cur);
- cur = next;
- next = next->next;
- }
- free(cur);
- }