标签:
堆栈:
//
// Created by mao on 16-9-16.
//
#ifndef UNTITLED_STACK_H
#define UNTITLED_STACK_H
#define TRUE 1
#define FALSE 0
typedef int STACK_TYPE;
typedef struct stack{
STACK_TYPE value;
struct stack *next;
} STACK;
void create_stack();
void destory_stack();
void push(STACK_TYPE value);
STACK_TYPE pop();
int isEmpty();
#endif //UNTITLED_STACK_H
stack.h
//
// Created by mao on 16-9-16.
//
#include <stdlib.h>
#include "stack.h"
static STACK *stack;
void create_stack()
{
stack = (STACK *)malloc(sizeof(STACK));
stack -> next = NULL;
}
void destory_stack()
{
STACK *pStack;
while((pStack = stack -> next) != NULL){
free(stack);
stack = pStack;
}
}
void push(STACK_TYPE value)
{
STACK *new = (STACK *)malloc(sizeof(STACK));
new -> next = stack;
new -> value = value;
stack = new;
}
STACK_TYPE pop()
{
STACK_TYPE value = stack -> value;
STACK *pStack = stack;
stack = stack -> next;
free(pStack);
return value;
}
int isEmpty()
{
return stack -> next == NULL ? TRUE : FALSE;
}
stack.c
#include <stdio.h>
#include "stack.h"
int main()
{
//堆栈
create_stack();
push(10);
push(20);
push(30);
pop();
push(22);
while(isEmpty() == FALSE){
printf("%d \t", pop());
}
}
main.c
运行:

队列:
当使用数组作为队列时,如果只是一端插入一端弹出,那么当尾部没有空间时,便无法插入元素,一种解决方法是使用“环绕”数组,新元素可以存储到以前删除元素所留出来的空间中,这种方法称为循环数组。
循环数组有个问题,当队列为空,或者为满时,首位的下标是一样的,无法判断出此时队列的状态,所以在队列的rear后加一个空余的不使用的位置,用来判断队列的状态是满队列,还是空队列。
当为满队列时:
(rear + 2) % QUEUE_SIZE = front
当为空队列时:
(rear + 1) % QUEUE_SIZE = front
队列实现:
// // Created by mao on 16-9-16. // #ifndef UNTITLED_QUEUE_H #define UNTITLED_QUEUE_H #define TRUE 1 #define FALSE 0 #define QUEUE_SIZE 100 #define ARRAY_SIZE (QUEUE_SIZE + 1) typedef int QUEUE_TYPE; static QUEUE_TYPE queue[ARRAY_SIZE]; static int front = 1; static int rear = 0; void Q_delete(); QUEUE_TYPE Q_first(); void Q_insert(QUEUE_TYPE value); int Q_isEmpty(); int Q_isFull(); #endif //UNTITLED_QUEUE_H
queue.h
//
// Created by mao on 16-9-16.
//
#include "queue.h"
#include <assert.h>
void Q_delete()
{
assert(Q_isEmpty() == FALSE);
front = (front + 1) % QUEUE_SIZE;
front = (front) % QUEUE_SIZE;
}
QUEUE_TYPE Q_first()
{
assert(Q_isEmpty() == FALSE);
return queue[front];
}
//队列插入数据,rear++
void Q_insert(QUEUE_TYPE value)
{
assert(Q_isFull() == FALSE);
rear = (rear + 1) % QUEUE_SIZE;
queue[(rear) % QUEUE_SIZE] = value;
}
int Q_isEmpty()
{
return (rear + 1) % QUEUE_SIZE == front ? TRUE: FALSE;
}
int Q_isFull()
{
return (rear + 2) % QUEUE_SIZE == front ? TRUE : FALSE;
}
queue.c
#include <stdio.h>
#include "queue.h"
int main()
{
//插入队列
Q_insert(10);
Q_insert(12);
Q_delete();
Q_insert(22);
Q_insert(30);
printf("%d\n", Q_first());
Q_delete();
printf("%d\n", Q_first());
Q_delete();
printf("%d\n", Q_first());
Q_delete();
return 1;
}
main.c
运行:

二叉树:
标签:
原文地址:http://www.cnblogs.com/yangxunwu1992/p/5877908.html