---
title: "动态栈"
author: "vergilwang"
date: "2011-10-31T15:47:00Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2014-02-15T16:27:36Z"
id: 2011432
url: "https://vergilwang.iteye.com/blog/2011432"
---

/*  
\* =====================================================================================  
\*  
\* Filename: dynamic\_stack.c  
\*  
\* Description:  
\*  
\* Version: 1.0  
\* Created: 2011年10月25日 16时53分20秒  
\* Revision: none  
\* Compiler: gcc  
\*  
\* Author: Wang Ran (), wangran51@126.com  
\* Company:  
\*  
\* =====================================================================================  
\*/  
#include &lt;stdio.h&gt;  
#include &lt;stdlib.h&gt;  
struct stack\_node  
{  
int data;  
struct stack\_node \*next\_ptr;  
};

void push(struct stack\_node\** node, int n);  
int pop(struct stack\_node\** node);  
int is\_empty(struct stack\_node* node);  
void print\_stack(struct stack\_node* node);  
void instructions(void);

int main()  
{  
struct stack\_node * stack\_ptr = NULL;//在第第一次push的时候NULL会被复制到top\_ptr-&gt;next\_ptr中  
//所以这句是必须的  
int i, choice, value;

for(i=0; i&lt;5; i++)  
{  
printf("Enter an interger:");  
scanf("%d", &value);  
push(&stack\_ptr, value);  
//print\_stack(stack\_ptr);  
}

for(i=0;i&lt;5;i++)  
{

if(!is\_empty(stack\_ptr))  
{  
printf("the poped value is %d\\n ", pop(&stack\_ptr));  
}  
print\_stack(stack\_ptr);  
}

printf("end of run \\n ");

return EXIT\_SUCCESS;  
}

void instructions(void)  
{  
printf("Enter choice: \\n 1:push\\n 2:pop\\n 3:end\\n ");  
}  
void push(struct stack\_node \** top\_ptr, int info)  
{  
struct stack\_node * new\_ptr;  
new\_ptr = malloc(sizeof (struct stack\_node));  
if(new\_ptr != NULL)  
{  
new\_ptr-&gt;data = info;  
new\_ptr-&gt;next\_ptr = \*top\_ptr;  
\*top\_ptr = new\_ptr;  
}  
else  
{  
printf("%d not inserted, No memory available. \\n", info);  
}  
}  
int pop(struct stack\_node\** top\_ptr)  
{  
struct stack\_node* temp\_ptr;  
int pop\_value;  
temp\_ptr = \*top\_ptr;  
pop\_value = (\*top\_ptr)-&gt;data;  
\*top\_ptr = (\*top\_ptr)-&gt;next\_ptr;  
free(temp\_ptr);  
return pop\_value;  
}  
void print\_stack(struct stack\_node* current\_ptr)  
{  
if(current\_ptr == NULL)  
{  
printf("the stack is empty.\\n");  
}  
else  
{  
while(current\_ptr != NULL)  
{  
printf("%d--&gt;", current\_ptr-&gt;data);  
current\_ptr = current\_ptr-&gt;next\_ptr;  
}  
printf("NULL\\n ");  
}  
}  
int is\_empty(struct stack\_node * top\_ptr)  
{  
return top\_ptr == NULL;  
}