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

C语言实现栈

2014-12-23 12:24 239 查看
/*参考《数据结构与 算法分析:C语言描述》*/ 
#include<stdio.h>
#include<stdlib.h>
#ifndef __cplusplus
#include<stdbool.h>   /*包含bool、true*/
#endif //__cplusplus
typedef char ElemType;
typedef struct Stack{
    ElemType data;
    struct Stack *next;
}Stack,*pStack;
/***************************************/
pStack CreateStack(void);
void Push(pStack ,ElemType );
bool IsEmpty(pStack);
void Pop(pStack );
int Top(pStack );
void MakeEmpty(pStack);
/***************************************/
pStack CreateStack(void)
{
    pStack S=(pStack)malloc(sizeof(Stack));
    if(S==NULL)
    {
        printf("申请内存失败!\n");
        return NULL;
    }
    S->next=NULL;
    return S; 
}
void Push(pStack S,ElemType a)
{
    pStack p=(pStack)malloc(sizeof(Stack));
    if(p==NULL)
    {
        printf("申请内存失败!\n");
        return;
    }
    p->data=a;
    p->next=S->next;
    S->next=p;
}
bool IsEmpty(pStack S) 
{
	if(S->next==NULL)
	{
		return true;
	}
	return false;
}

void Pop(pStack S)
{
	if(IsEmpty(S))
	{
		printf("错误:试图在空栈弹出元素!\n");
	}
	else
	{
		pStack p=S->next;
		S->next=S->next->next;
		free(p);
	}
}
int Top(pStack S)
{
	if(IsEmpty(S))
	{
		printf("不能从空栈中获得元素\n");
                return 0;
	}
	else
	{
		return S->next->data;
	}
}
void MakeEmpty(pStack S)
{
	while(!(IsEmpty(S)))
	{
		Pop(S);
	}
}
int main(void)
{
    pStack S;
    S=CreateStack();
    char c;
    c=getc(stdin);
    while(c!='\n')
    {
    	Push(S,c);
    	c=getc(stdin);
    }
    while(!IsEmpty(S))
    {
    	printf("%c\n",Top(S));
    	Pop(S);
    }
    system("pause");
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: