顺序栈
sqstack.h
#ifndef __LINKLIST_H__
#define __LINKLIST_H__
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
typedef struct NODE{
int data[MAX];
int top;
}sqstack;
sqstack* stack_create();
int stack_push(sqstack* s,int value);
int stack_pop(sqstack* s);
#endif
sqstack.c
#include "sqstack.h"
sqstack* stack_create(int len)
{
sqstack*S = NULL;
S = (sqstack*)malloc(sizeof(sqstack));
S->top = -1;
return S;
}
int stack_push(sqstack* s,int value)
{
s->top = s->top+1;
s->data[s->top] = value;
return 1;
}
int stack_pop(sqstack* s)
{
int value = s->data[s->top];
s->top = s->top-1;
return value;
}
sqstack_text.c
#include "sqstack.h"
void main()
{
sqstack *S = NULL;
S = stack_create(10);
stack_push(S,1);
stack_push(S,2);
stack_push(S,3);
stack_push(S,4);
stack_push(S,5);
printf("%d\t",stack_pop(S));
printf("%d\t",stack_pop(S));
printf("%d\t",stack_pop(S));
printf("%d\t",stack_pop(S));
printf("%d\t",stack_pop(S));
}
Makefile
sqstack_text:sqstack.o sqstack_text.c
gcc sqstack.o sqstack_text.c -o sqstack_text
sqstack.o:sqstack.c sqstack.h
gcc sqstack.c -c -o sqstack.o
.PHONY:clean
clean:
rm -rf sqstack.o sqstack_text
Makefile
root@ubuntu:/home/yqj/desktop/顺序栈# ./sqstack_text
5 4 3 2 1
链式栈
建立栈底
寻找栈顶 --> push / pop
linkstack.h
#ifndef __LINKLIST_H__
#define __LINKLIST_H__
#include <stdio.h>
#include <stdlib.h>
typedef struct NODE{
int data;
struct NODE*next;
}liststack;
liststack * stack_create();
void stack_push(liststack*LS,int value);
int stack_pop(liststack*LS);
#endif
linkstack.c
#include "liststack.h"
liststack * stack_create()
{
liststack*LS = NULL;
LS = (liststack*)malloc(sizeof(liststack));
LS->data = 0;
LS->next = NULL;
return LS;
}
void stack_push(liststack*LS,int value)
{
liststack*P=LS;
liststack*Q=NULL;
Q = (liststack*)malloc(sizeof(liststack));
while((P->next)!=NULL)
{
P = P->next;
}
Q->data = value;
Q->next = NULL;
P->next = Q;
}
int stack_pop(liststack*LS)
{
int value;
liststack*P=LS;
liststack*Q=LS;
while((P->next->next)!=NULL)
{
P = P->next;
}
Q = P->next;
P->next = NULL;
value = Q->data;
free(Q);
return value;
}
liststack_test.c
#include "liststack.h"
void main()
{
liststack *LS = NULL;
LS = stack_create();
stack_push(LS,10);
stack_push(LS,20);
stack_push(LS,30);
stack_push(LS,40);
stack_push(LS,50);
printf("%d\t",stack_pop(LS));
printf("%d\t",stack_pop(LS));
printf("%d\t",stack_pop(LS));
printf("%d\t",stack_pop(LS));
printf("%d\t",stack_pop(LS));
}
Makefile
liststack_text:liststack.o liststack_text.c
gcc -g liststack.o liststack_text.c -o liststack_text
liststack.o:liststack.c liststack.h
gcc -g liststack.c -c -o liststack.o
.PHONY:clean
clean:
rm -rf liststack.o liststack_text
运行结果
root@ubuntu:/home/yqj/desktop/链式栈# ./liststack_text
50 40 30 20 10