您的位置:首页 > 编程语言 > C语言/C++

多文件编程链状结构实现栈的操作 c语言版

2014-03-26 00:00 639 查看
动态开辟存储空间模拟栈的操作:

stack.c

#include <stdio.h>
#include <stdlib.h>
#include "stack.h"
typedef struct node{
int num;
struct node *p_next;
}node;
static node head,tail;
void push(int number){
node *tmp = (node *)malloc(sizeof(node));
tmp->num = number;
tmp->p_next = head.p_next;
head.p_next = tmp;
}
int pop(){
int number;
if (head.p_next != &head){
node *tmp = head.p_next;
head.p_next = head.p_next->p_next;
number = tmp->num;
free(tmp);
tmp = NULL;
}
return number;
}
int top(){
return head.p_next == &tail ? 0 : head.p_next->num;
}
int empty(){
return head.p_next == &tail;
}
int full(){
return 0;
}
int size(){
node *p_node =&head;
int cnt = 0;
for (p_node = &head;p_node != &tail;p_node = p_node->p_next){
node *p_lnext = p_node->p_next;
if (p_lnext != &tail){
cnt++;
}
}
return cnt;
}
void init(){
head.p_next = &tail;
}
void deinit(){
node *p_node;
while (head.p_next != &tail){
p_node = head.p_next;
head.p_next = head.p_next->p_next;
free(p_node);
p_node = NULL;
}
}



stack.h

#ifndef __STACK_H__
#define __STACK_H__
void push(int number);
int pop();
int top();
int empty();
int full();
int size();
void init();
void deinit();
#endif

main.c

#include<stdio.h>
int main()
{
init();
push(1);
push(3);
push(4);
printf("size = %d\n",size());
printf("%d\n",pop());
printf("%d\n",pop());
printf("%d\n",pop());
printf("size = %d\n",size());
if(empty()) printf("the stack is empty.\n");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息