c语言实现的栈---链表+数组
1.数组实现的栈
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXSIZE 5
/**
*数组实现的栈,缺点,容量固定
**/
typedef struct{
int data[MAXSIZE];
int index;
}Stack;
Stack s;
/**
*入栈,成功返回1,否则0
**/
int push(int e){
int rt = 0;
if(s.index < MAXSIZE-1){
s.data[++s.index] = e;
}else{
rt = -1;
}
return rt;
}
/**
*初始化栈
*/
int clear(void){
s.index = -1;
return 0;
}
/**
*判断栈是否为空
**/
int isempty(void){
return (s.index == -1)?1:0;
}
/**
*出栈,弹出栈顶元素
**/
int pop(void){
int t=0;
if(s.index != -1){
t=s.data[s.index--];
}
return t;
}
/**
*栈内元素打印
*/
int displaystack(void){
int p=s.index;
while(s.index!=-1){
printf("currentdata:%d\n",s.data[s.index--]);
}
s.index = p;
return 0;
}
int main(void){
clear();
puts("after push:");
push(1);
push(2);
push(3);
push(4);
push(5);
push(6);
printf("s.index=%d:\n",s.index);
displaystack();
puts("\nafter pop");
pop();
displaystack();
return 0;
}
2.链表实现
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/**
*链表实现的栈
**/
typedef struct linklist{
int data;
struct linklist *next;
struct linklist *pre;
}Link;
typedef struct{
int index;//栈顶
int empty;//链表是否为空标志
Link *head;
}StackLink;
StackLink s;
/**
*入栈
**/
int push(int e){
Link *element,*end;
if(s.index==0){
end = (Link *)malloc(sizeof(Link));
s.empty = -1;
}else{
end = s.head;
}
element = (Link *)malloc(sizeof(Link));
element->data = e;
element->pre = end;
element->next = NULL;
end->next = element;
end = element;
s.index ++;
s.head = end;
return 0;
}
/**
*标志位设为空
**/
int clear(){
s.empty = 0;
return 0;
}
/**
*判断栈是否为空
**/
int isempty(void){
return (s.empty==0)?1:0;
}
/**
*出栈,弹出栈顶元素
**/
int pop(void){
int t=0;
if(s.index != 0&&s.empty == -1){
s.index --;
Link *temp,*p;
t=s.head->data;
temp=s.head;
p = temp->pre;
free(s.head);
s.head = p;
}else{
s.empty = 0;
}
return t;
}
/**
*栈内元素打印
*/
int displaystack(void){
Link *t = s.head;
while(s.head->pre!=NULL){
printf("currentdata:%d\n",s.head->data);
s.head=s.head->pre;
}
s.head = t;
return 0;
}
int main(void){
clear();
puts("after push:");
for(int i=0;i<100;i++)
push(i);
printf("s.index=%d:\n",s.index);
displaystack();
puts("\nafter pop");
pop();
pop();
displaystack();
return 0;
}

浙公网安备 33010602011771号