只是简单的建立和输出,剩下的一些操作参考线性表相关内容 先进后出
线性栈
#include<stdio.h> #include<stdlib.h> #define max 10 char data[max]; int top = 0; void show(char data[],int top) { int t; t = top-1; for (; t >= 0; t--) printf("%c", data[t]); } int push(char ch) { if (top > max) { printf("out error"); return 0; } data[top] = ch; top++; return 1; } int main() { int i; char s[10] = "abcdefghef"; for (i = 0; i < 10; i++) push(s[i]); show(data, top); }
链栈 说真的这些临时变量用的我自己都恶心
#include<stdio.h> #include<malloc.h> struct node { char data; struct node *next; }; typedef struct node node; node *top=NULL; int push(char ch) { node *p; p = (node *)malloc(sizeof(node)); if (!p)return 0; p->data = ch; p->next = top; top= p; return 1; } int pop(char *ch) { node *p; p = top; if (!p)return 0; ch = p->data; top = top->next; free(p); } show(node *top) { node *p = top; while (p != NULL) { printf("%c ", p->data); p = p->next; } } void main() { int i; char s[] = "abcdefghea"; for (i = 0; i < 10; i++) { push(s[i]); } node *p = top; while (p != NULL) { printf("%c ", p->data); p = p->next; } printf(" "); char ch='a'; pop(&ch); show(top); printf(" "); printf("%c", ch); }
队列 这个特点就是先进先出
有毛病的代码 出队后不能及时删除出队的数据、用的是循环队列,总觉得哪里不对但是又说不上来,好像又没错如果是循环队列的话好像这种现象说明我的循环正确
#include<stdio.h> #define max 10 char data[max]; int head = -1, tail = -1; int push(char ch) { if (tail == (head + max - 1) % max) { printf("队满 "); return 0; } data[tail] = ch; tail = (max + tail+1) % max; return 1; } show() { int i; i = head; while (data[i] != '