[转载]顺序栈的C语言实现

// 程 式 名: LinkStack.c
// 程式功能: 链栈的实现
// 功能描述: 置栈空、判栈空、压栈、出栈、取栈顶元素 

//http://student.zjzk.cn/course_ware/data_structure/web/xianxingbiao/xianxingbiao2.3.1.2.htm 


#include 
<stdio.h>
#include 
<stdlib.h>       // 包含exit();
typedef char DataType;    // 假定数据类型为字符
typedef struct stacknode{
 DataType data;
 
struct stacknode *next;
}
StackNode;
typedef 
struct{
 StackNode 
*top;       // 栈顶指针
}
LinkStack;

// 置栈空
void Initial(LinkStack *s)
{
 s
->top = 0;
}


// 判栈空
int IsEmpty(LinkStack *s)
{
 
return s->top == 0;
}


// 压栈
void Push(LinkStack *s, DataType x)
{
 
// 将元素x插入链栈头部
 StackNode *= (StackNode *)malloc(sizeof(StackNode));
 p
->data = x; 
 p
->next = s->top; 
 s
->top = p;       
}


// 出栈
DataType Pop(LinkStack *s)
{
 DataType x;
 StackNode 
*= s->top;
 
if (IsEmpty(s))
 
{
  printf(
"栈为空\n");
  exit(
1);
 }

 x 
= p->data;
 s
->top = p->next;
 free(p);
 
return x;
}


// 取栈顶元素
DataType Top(LinkStack *s)
{
 
if (IsEmpty(s))
 
{
  printf(
"栈为空\n");
  exit(
1);
 }

 
return s->top->data;
}


void main()
{
 LinkStack s;
 DataType first,sec;
 Initial(
&s);
 Push(
&s, 'a');
 Push(
&s, 'b');
 first 
= Top(&s);
 Pop(
&s);
 sec 
= Top(&s);
 printf(
"%c,%c\n", first, sec);
}
 

原文地址:https://www.cnblogs.com/fx2008/p/2193063.html