首页 > 代码库 > 栈和队列
栈和队列
只是简单的建立和输出,剩下的一些操作参考线性表相关内容 先进后出
线性栈
#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 =http://www.mamicode.com/ 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("\n"); char ch=‘a‘; pop(&ch); show(top); printf("\n"); 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("队满\n"); return 0; } data[tail] = ch; tail = (max + tail+1) % max; return 1; } show() { int i; i = head; while (data[i] != ‘\0‘) { printf("%c ", data[i]); i++; } } int pop(char *ch) { if (head == tail) { printf("队空\n"); return 0; } *ch = data[head]; head = (max + head + 1) % max; return 1; } main() { char s[] = "abcdefghee"; int i; for (i = 0; i < 10; i++) { push(s[i]); } show(); char ch=‘p‘; pop(&ch); printf("出队元素:%c\n", ch); printf("队内元素:\n"); show(); printf("队内元素:\n"); for (i = 0; i < 10; i++) { push(s[i]); }show(); for (i = 0; i < 10; i++) { pop(&ch); printf("出队元素:%c\n", ch); } }
链表栈
#include<stdio.h> #include<stdlib.h> struct node { char data; struct node *next; }; typedef struct node node; node *head=NULL, *tail=NULL; int push(char ch) { node *p; p = (node *)malloc(sizeof(node)); if (!p)return 0; p->data = http://www.mamicode.com/ch;"%c",head->data); } else { tail->next = p; printf("%c\n", tail->data); } tail = p; return 1; //无法理解两个节点之间是如何相连的 } int pop(char *p_y) { node *p; if (head == NULL) return(1); *p_y = head->data; p = head; head = head->next; free(p); return(0); } main() { char s[] = "abcdefghee"; int i; for (i = 0; i < 10; i++) { push(s[i]); } node *p; p = head; while (p != NULL) { printf("%c ", p->data); p = p->next; } printf("\n"); char ch; pop(&ch); }
栈和队列
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。