1.链表实现栈
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
}node;
node *head = NULL;
node *mk_node(int data)
{
node *p = (node*)malloc(sizeof(node));
if(p == NULL)
{
printf("ÉêÇëÄÚ´æʧ°Ü");
exit(1);
}
p->data = data;
return p;
}
int head_insert(node *p)
{
p->next = head;
head = p;
}
int head_insert_l2b(node *p)
{
if(head == NULL)
{
p->next = head;
head = p;
return ;
}
if(head->data > p->data)
{
p->next = head;
head = p;
return ;
}
node *pre = head;
while(pre->next != NULL)
{
if((pre->data < p->data)&&(pre->next->data > p->data))
{
p->next = pre->next;
pre->next = p;
return ;
}
pre = pre->next;
}
p->next = pre->next;
pre->next = p;
return ;
}
int free_node(node *p)
{
free(p);
}
int delete_node(node *p)
{
node *pre = head;
while(pre->next != NULL)
{
if(pre->next = p)
{
pre->next = p->next;
}
pre = pre->next;
}
}
int destroy()
{
node *pre = head;
node *p = NULL;
while(pre->next != NULL)
{
p = pre->next;
delete_node(pre);
pre = p;
}
}
int traverse()
{
node *pre = head;
while(pre != NULL)
{
printf("%d ",pre->data);
pre = pre->next;
}
printf("\n------------------\n");
}
int reverse()
{
node *nhead = NULL;
if(head == NULL)
{
return ;
}
node *pre = head;
node *p = NULL;
while(pre->next != NULL)
{
p = pre->next;
pre = pre->next;
nhead->next = p;
nhead = p;
}
head = nhead;
}
int push(int data)
{
node *p = mk_node(data);
head_insert(p);
}
int pop()
{
node*pre = head;
node *p = NULL;
while(pre != NULL)
{
p = pre->next;
printf("pop():%d\n",pre->data);
free_node(pre);
pre = p;
}
}
int is_empty()
{
if(head == NULL)
{
return 1;
}else
{
return 0;
}
}
int main()
{
push(1);
traverse();
push(2);
traverse();
push(3);
traverse();
pop();
return 0;
}
2. 数组实现栈
#include<stdio.h>
#define STACK_SIZE 512
char stack[STACK_SIZE];
int top = 0;
void push(char c)
{
stack[top] = c;
top++;
}
char pop()
{
--top;
return stack[top];
}
int is_empty()
{
return top == 0;
}
int is_full()
{
return top == STACK_SIZE;
}
int main()
{
push(1);
push(2);
push(2);
while(!is_empty())
{
printf("出栈元素 %d",pop());
}
printf("\n");
return 0;
}