前一阵子装系统,两天装CentOS,RHEL,Fedora,Mint,Ubuntu,结果不小心把我的老的Ubuntu里面的code都给弄丢了。现在既然学会了利用github,我就再写一份,一来复习一下,二来万一将来需要写类似的代码,可以快速的拿来用。
代码都在需要的筒子可以去取一份。
stack.h
- #ifndef __STACK_H__
- #define __STACK_H__
- typedef struct Stack_node
- {
- void *data;
- struct Stack_node* next;
- }Stack_node;
- typedef struct Stack
- {
- struct Stack_node* head;
- }Stack;
- int stack_init(struct Stack* self);
- int stack_empty(struct Stack* self);
- int stack_push(struct Stack* self,void *data);
- void* stack_pop(struct Stack* self);
- #endif
- #include "stack.h"
- #include<stdlib.h>
- int stack_init(struct Stack* self)
- {
- if(self == NULL)
- {
- return -1;
- }
- self->head = NULL;
- return 0;
- }
- int stack_empty(struct Stack* self)
- {
- return self->head == NULL;
- }
- int stack_push(struct Stack* self,void *data)
- {
- struct Stack_node* newnode = malloc(sizeof(struct Stack_node));
- if(newnode == NULL)
- return -1;
- else
- {
- newnode->data = data;
- newnode->next = self->head;
- self->head = newnode;
- return 0;
- }
- }
- void* stack_pop(struct Stack* self)
- {
- if(self->head == NULL)
- return NULL;
- void* data = self->head->data;
- struct Stack_node* next = self->head->next;
- free(self->head);
- self->head = next;
- return data;
- }
- #include "stack.h"
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- int test_stack()
- {
- int data_array[10] = {0};
- struct Stack stack;
- int i = 0;
- int ret = stack_init(&stack);
- if(ret < 0)
- {
- fprintf(stderr,"stack init failed\n");
- }
- srand(time(NULL));
- for(i = 0;i<10;i++)
- {
- data_array[i] = rand()%100;
- printf("%d\t",data_array[i]);
- stack_push(&stack,&data_array[i]);
- }
- fprintf(stdout,"\n");
-
- while(stack_empty(&stack) == 0)
- {
- int *p = (int *)stack_pop(&stack);
- fprintf(stdout,"%d\t",*p);
- }
- fprintf(stdout,"\n");
-
- return 0;
- }
- int main()
- {
- test_stack();
- return 0;
- }
- root@manu:~/code/c/self/stack# make
- gcc -Wall -o stack.o -c stack.c
- gcc -Wall -o stack_test.o -c stack_test.c
- gcc -o test stack.o stack_test.o
- root@manu:~/code/c/self/stack# ./test
- 81 51 5 78 84 91 86 83 14 43
- 43 14 83 86 91 84 78 5 51 81
参考文献:
1 算法:C语言实现