C语言链栈与顺序栈的实现
顺序栈
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 10
typedef int DataType;
typedef struct {
DataType buf[MAX];
DataType top;
}SeqStack;
SeqStack *create_empty_stack(){
SeqStack *stack = NULL;
stack = (SeqStack *)malloc(sizeof(SeqStack));
if(stack == NULL){
printf("faild to malloc");
return NULL;
}
memset(stack,0,sizeof(stack));
return stack;
}
void init_seqstack(SeqStack *stack){
stack->top = 0;
}
int is_empty(SeqStack *stack){
if(stack->top = -1){
return 0;
}
return 1;
}
void push(SeqStack *stack,DataType data){
stack->buf[stack->top] = data;
stack->top++;
}
void pop(SeqStack *stack){
stack->top--;
}
int main(int argc, char const *argv[])
{
SeqStack *p = create_empty_stack();
push(p,1);
push(p,2);
push(p,3);
pop(p);
return 0;
}
链栈
要注意的是push的时候需要传入二级指针top
#include <stdio.h>
#include <stdlib.h>
typedef int DataType;
typedef struct node
{
DataType data;
struct node *next;
} LinkStack;
LinkStack *create_empty_linkstack()
{
LinkStack *top = NULL;
top = (LinkStack *)malloc(sizeof(LinkStack));
if (top == NULL)
{
printf("faild to malloc LinkStack\n");
return NULL;
}
top->next = NULL;
return top;
}
int is_empty(LinkStack *top)
{
if(top->next == NULL){
printf("linkstack is empty\n");
}
return top->next == NULL ? 0 : 1;
}
LinkStack *push(LinkStack **top, DataType data)
{
LinkStack *newnode = NULL;
newnode = (LinkStack *)malloc(sizeof(LinkStack));
if (newnode == NULL)
{
printf("faild to malloc LinkStack\n");
}
newnode->data = data;
newnode->next = *top;
*top = newnode;
//return top;
}
void pop(LinkStack *top){
if(!is_empty(top)){
printf("linkstack is empty\n");
exit(EXIT_FAILURE);
}
top = top->next;
}
int getTop(LinkStack *top){
is_empty(top);
return top->data;
}
int main(int argc, char const *argv[])
{
LinkStack *top = create_empty_linkstack();
push(&top,2);
push(&top,8);
push(&top,6);
is_empty(top);
printf("top value:%d\n",getTop(top));
return 0;
}
输出结果