学习编程数据结构是核心的知识,下面我和大家分享一些数据结构的知识
栈的应用源码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#define ALLOC_SIZE 512
typedef int KEY_TYPE;
typedef struct _stack {
KEY_TYPE *base;
int top;
int stack_size;
} stack;
void init_stack(stack *s) {
s->base = (KEY_TYPE*)calloc(ALLOC_SIZE, sizeof(KEY_TYPE));
assert(s->base);
s->top = 0;
s->stack_size = ALLOC_SIZE;
}
void destroy_stack(stack *s) {
assert(s);
free(s->base);
s->base = NULL;
s->stack_size = 0;
s->top = 0;
}
void push_stack(stack *s, KEY_TYPE data) {
assert(s);
if (s->top >= s->stack_size) {
s->base = realloc(s->base, (s->stack_size + ALLOC_SIZE) * sizeof(KEY_TYPE));
assert(s->base);
s->stack_size += ALLOC_SIZE;
}
s->base[s->top] = data;
s->top ++;
}
void pop_stack(stack *s, KEY_TYPE *data) {
assert(s);
*data = s->base[--s->top];
}
int empty_stack(stack *s) {
return s->top == 0 ? 0 : 1;
}
int size_stack(stack *s) {
return s->top;
}
int main() {
stack s;
init_stack(&s);
int i = 0;
for (i = 0;i < 1000;i ++) {
push_stack(&s, i+1);
}
while (empty_stack(&s)) {
int data;
pop_stack(&s, &data);
printf("%4d", data);
}
printf("\n");
destroy_stack(&s);
}
?快速排序算法
#include <stdio.h>
int quick_sort(int *data,int left,int right)
{
if(left >= right)
return 0;
int i = left;
int j = right;
int key = data[i];
while(i < j)
{
while(i < j && key < data[j])
{
j--;
}
data[i] = key;
while(i < j && key > data[i])
{
i++;
}
data[j] = data[i];
quick_sort(data,left,i-1);
quick_sort(data,i+1,right);
}
return 0;
}
int sort(int *data,int length)
{
quick_sort(data,0,length);
}
int main()
{
int data[10] = {1,5,3,7,8,9,2,4,0,6};
sort(data,10);
for(int i = 0;i <10;i++)
{
printf("%4d\n",data[i]);
}
}
?这时就要考虑用到KMP算法了
大家需要学习资源可以QQ联系我:514475924
|