c语⾔栈头⽂件,C语⾔——栈(Stack)源码:
⽅式⼀:
头⽂件:
#ifndef _STACK_H
#define _STACK_H
struct node;
typedef struct node* stack;
/* 判断栈是否为空 */
int isEmpty(stack s);
/* create stack */
stack createStack(void);
/
* release stack */
void releaseStack(stack s);
/* ⼊栈 */
void push(void *data,stack s);
/* 取栈顶元素 */
void* top(stack s);
/* 出栈 */
void pop(stack s);
#endif
struct node{
void* data;
struct node* next;
};
#include #include #include "stack.h"
int isEmpty(stack s)
{
return s->next == NULL;
}
stack createStack(void)
{
if (s == NULL){
puts("create error");
return 0;
}
else{
s->next = NULL;
s->data = NULL;
return s;
}
}
void releaseStack(stack s)
{
struct node* element;
element = s;
while (element){
s = s->next;
free(element);
element = s;
}
}
c语言struct头文件void push(void *data, stack s)
{
struct node* element;
element = malloc(sizeof(struct node)); if (element == NULL)
puts("create ndoe fail . .");
else{
element->data = data;
element->next = s->next;
s->next = element;
}
}
if (isEmpty(s)){
puts("empty stack in top");
return NULL;
}
return s->next->data;
}
void pop(stack s)
{
if (isEmpty(s))
puts("empty stack in pop");
else{
struct node* element;
element = s->next;
s->next = element->next;
free(element);
}
} ⽅式⼆:
#ifndef _STACK2_H
#define _STACK2_H
#define MIN (5)
struct stackArray;
typedef struct stackArray* stack; /* 判断stack是否为空 */
int isEmpty2(stack s);
/* 判断stack是否已满 */
int isFull2(stack s);
/* 创建stack */
stack createStack2(int maxNum); /* release stack */
void release2(stack s);
/* 进栈 */
void push2(void* data,stack s);
/* 出栈 */
void pop2(stack s);
#endif
struct stackArray{
int capacity;
int topOfStack;
void** array;
};
#include #include #include "stack2.h" int main()
{
stack s;
s = createStack2(6);
push2("hello", s);
push2("word", s);
push2("...", s);
push2("hello", s);
push2("stack", s);
push2("...", s);
push2("hello word", s);
push2("hello word", s);
printf("%s\n", top2(s));
pop2(s);
printf("%s\n", top2(s));
pop2(s);
printf("%s\n", top2(s));
release2(s);
return 0;
}
int isEmpty2(stack s)
{
return s->topOfStack == -1;
{
return s->topOfStack == s->capacity - 1; }
stack createStack2(int maxNum)
{
if (maxNum < MIN){
puts("stack⼤⼩必须⼤于5");
return -1;
}
stack s;
s = malloc(sizeof(struct stackArray));
if (s == NULL){
puts("create stack error");
return -1;
}
s->array = malloc(sizeof(void*)*maxNum); if (s->array == NULL){
puts("创建stack失败");
return -1;
}
s->capacity = maxNum;
s->topOfStack = -1;
return s;
}
void release2(stack s)
{
if (s != NULL){
free(s->array);
free(s);
}
}
void push2(void* data, stack s)
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论