}
2.队列算法
#include<stdio.h> #include<stdlib.h> typedef struct Queue { int * pBase; int front; int rear; }QUEUE; void init(QUEUE *); bool en_queue(QUEUE *, int); void traverse_queue(QUEUE *); bool full_queue(QUEUE *); bool out_queue(QUEUE *,int *); bool emput_queue(QUEUE *pQ); int main(void) { QUEUE Q; int avl; init(&Q); en_queue(&Q,1); en_queue(&Q, 2); en_queue(&Q, 3); en_queue(&Q, 4); en_queue(&Q, 5); en_queue(&Q, 6); traverse_queue(&Q); if (out_queue(&Q, &avl)) printf("出队的元素是%d\n", avl); else printf("失败\n"); traverse_queue(&Q); system("pause"); return 0; } void init(QUEUE *pQ) { pQ->pBase = (int *)malloc(sizeof(int) * 6); pQ->front = pQ->rear = 0; } bool full_queue(QUEUE * pQ) { if ((pQ->rear + 1) % 6 == pQ->front) return true; else return false; } bool en_queue(QUEUE * pQ, int avl) { if(full_queue(pQ)) return false; else { pQ->pBase[pQ->rear] = avl; pQ->rear = (pQ->rear + 1) % 6; return true; } } void traverse_queue(QUEUE * pQ) { int i = pQ->front; while (i!=pQ->rear) { printf("%d ", pQ->pBase[i]); i = (i + 1) % 6; } printf("\n"); return; } bool emput_queue(QUEUE *pQ) { if (pQ->front == pQ->rear) return true; else return false; } bool out_queue(QUEUE *pQ,int *pVal) { if (emput_queue(pQ)) { return false; } else { *pVal = pQ->pBase[pQ->front]; pQ->front = (pQ->front + 1) % 6; return true; } }
3.栈的算法
/****/ #include<stdio.h> #include<malloc.h> #include<stdlib.h> typedef struct Node { int data;//元素 struct Node *pNext;//结点 }NODE,*PNODE; typedef struct Stack { PNODE pTop;//顶部 PNODE pBottom;//底部 }STACK,*PSTACK; void init(PSTACK);//建一个空栈 void push(PSTACK,int );//入栈 void straverse(PSTACK); bool empty(PSTACK pS); bool pop(PSTACK pS, int *i); void clear(PSTACK pS); int main(void) { int val = 99; STACK S; //等价于struct Stack S init(&S); push(&S,1); push(&S,99); push(&S, 100); straverse(&S); if (pop(&S, &val)) printf("出站成功"); else printf("NO"); printf("\n"); straverse(&S); clear(&S); straverse(&S); system("pause"); return 0; } void init(PSTACK pS ) { pS->pTop = (PNODE)malloc(sizeof(NODE)); if (pS->pTop == NULL) { printf("分配失败!!"); exit(-1); } else { pS->pBottom = pS->pTop; pS->pBottom->pNext = NULL; } } void push(PSTACK pS, int val) { PNODE pNew = (PNODE)malloc(sizeof(NODE)); pNew->data = val; pNew->pNext = pS->pTop; pS->pTop = pNew; return; } void straverse(PSTACK pS) { PNODE p = pS->pTop; while (p != pS->pBottom) { printf("%d ", p->data); p = p->pNext; } printf("\n"); return; } bool empty(PSTACK pS) { if (pS->pTop == pS->pBottom) return true; else return false; } bool pop(PSTACK pS, int * pVal) { if (empty(pS)) { return false; } else { PNODE r = pS->pTop; *pVal = r->data; pS->pTop = r->pNext; free(r); r = NULL; return true; } } void clear(PSTACK pS) { if (empty(pS)) { return; } else { PNODE p = pS->pTop; PNODE q = NULL; while (p != pS->pBottom) { q = p->pNext; free(p); p = q; } pS->pTop = pS->pBottom; } }