您的位置:首页 > 理论基础 > 数据结构算法

数据结构——栈

2016-01-25 15:39 471 查看

一:动态数组堆栈

用一个指针代替数组,然后可以用malloc函数来动态建立一个大小由自己定的数组
代码如下:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int *s;
int stacksize;
int top = -1;

void create(int num) //建立一个空栈
{
stacksize = num;
s= (int*)malloc(stacksize*sizeof(int)); //动态数组
}
void push(int e) //入栈函数
{
s[++top] = e;
}
int gettop()   //取得栈顶元素
{
return s[top];
}
void pop()     //删除栈顶元素
{
top--;
}

int main()
{
int size;
scanf("%d", &size);
create(size);
push(1);
push(2);
while (top != -1)
{
printf("%d ", gettop());
pop();
}
printf("\n");
return 0;
}


二:链式堆栈

用链表表示栈,可以插入一个分配一个空间,就不用一开始分配空间了
代码如下:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
}TYPE;

TYPE *s;

void push(int e)
{
TYPE *newnode;
newnode = (TYPE*)malloc(sizeof(TYPE));
newnode->data = e;
newnode->next = s;
s = newnode;
}
void pop()
{
TYPE *newnode;
newnode = s;
s = s->next;
free(newnode);
}
void print()
{
TYPE *stack;
stack = s;
while (stack != NULL)
{
printf("%d ", stack->data);
stack = stack->next;
}
printf("\n");
}
int gettop()
{
return s->data;
}
int is_empty()  //判断栈是否为空栈函数
{
return s == NULL;
}
void clean()    //清空整个分配空间函数
{
while (!is_empty)
pop();
}

int main()
{
push(10); push(9); push(7); push(6); push(5);
push(4);  push(3); push(2); push(1); push(0);
printf("push压入数值后:\n");
print();
printf("\n");
pop();
pop();
printf("经过pop弹出几个元素后的堆栈元素:\n");
print();
printf("\n");
printf("top()调用出来的值: %d\n", gettop());
clean();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: