当先锋百科网

首页 1 2 3 4 5 6 7
记录一下自己学习过程中写的代码。以下是我看严蔚敏老师的数据结构教材后,结合教材所讲用C语言实现了关于栈的链式表示及其实现的基本操作,供以后复习所用。 
编译软件:VC++6.0 

测试用例结果截图如下:


源代码如下:

/********************************** 
栈的链式表示和实现(完整代码,C实现)
Author:大地在我腳下 
Date:2016-7-27
Email:[email protected] 
**********************************/  
#include<stdio.h>
#include<stdlib.h>

typedef struct SNode  
{  
 int data;  
 struct SNode *next;  
}SNode, *StackNode;  

typedef struct  Stack 
{  
 StackNode Top;  
 StackNode Bottom;
 int Stacksize;//栈的大小 
}Stack, *SqStack;  

SqStack CreateStack();
bool Push(SqStack,int);
bool Empty(SqStack); 
int Pop(SqStack);
void Traverse(SqStack);
void Destroy(SqStack);
void Clear(SqStack);
int Stacklength(SqStack);
int GetTop(SqStack);

void main()
{
//创建一个空的栈,pStack指针指向该栈  
SqStack pStack= CreateStack();  

//进行入栈操作,之后遍历输出栈内数据
Push(pStack,6);
Push(pStack,25);
Push(pStack,89);
Push(pStack,127);
Push(pStack,888);
Traverse(pStack);

//栈的长度
printf("Now the length of stack is:%d\n",Stacklength(pStack));

//取出栈顶元素
if(Empty(pStack)) 
    printf("\nNow the stack is empty!");
else printf("\nNow the top of stack is:%d\n",GetTop(pStack));

//进行出栈操作,之后遍历输出
if(Empty(pStack)) 
   printf("\nNow the stack is empty!");
else
{printf("\nThe pop data is:%d\n",Pop(pStack));
 printf("pop succeed!\n");
 Traverse(pStack);
}

//重新输出栈的长度
printf("Now the length of stack is:%d\n",Stacklength(pStack));

//重新取出栈顶元素
if(Empty(pStack)) 
    printf("\nNow the stack is empty!");
else printf("\nNow the top of stack is:%d\n",GetTop(pStack));

//清空栈,并输出清空后栈中的数据  
Clear(pStack);  
printf("\ndata cleared!\n");  
Traverse(pStack);  
}

//建立带头结点的栈
SqStack CreateStack()  
{StackNode p=(StackNode)malloc(sizeof(SNode));
SqStack q=(SqStack)malloc(sizeof(Stack));
if(!p||!q) 
   {printf("Malloc failed!");
    exit(-1);
   }
p->data=0;
q->Top=q->Bottom=p;
q->Bottom->next=NULL;
q->Stacksize=0;
return q;
}

//进栈
bool Push(SqStack S,int e)
{StackNode p=(StackNode)malloc(sizeof(SNode));
if(!p) 
   {printf("Malloc failed!");
    exit(-1);
   }
p->data=e;
p->next=S->Top;
S->Top=p;
S->Stacksize++;
return true;
}

//判断栈是否为空栈
bool Empty(SqStack S)
{if(S->Top->next) return false;
else return true;
}

//出栈,将出栈得到的值保存在e中,避免丢失
int Pop(SqStack S)
{StackNode  q;
 int e;
q=S->Top;
e=q->data;
S->Top=S->Top->next;
free(q);
q=NULL;
S->Stacksize--;
return e;
}

//遍历并输出栈内数据
void Traverse(SqStack S)
{StackNode  q=S->Top;  
printf("Now datas int the stack are:\n");
while(q->next)
{printf("%d",q->data);
q=q->next;
putchar(32);
}
printf("\n");
}

//销毁栈,栈不再存在
void Destroy(SqStack S)
{StackNode  p,q=S->Top;
while(q->next)
{p=q->next;
free(q);
q=p;
}
S->Top=S->Bottom;
}

//清空栈,把栈置为空栈
void Clear(SqStack S)
{if(Empty(S)) printf("\nNow the stack is empty!");
else  Destroy(S);
}

//栈的长度,即栈内元素个数
int Stacklength(SqStack S)
{return S->Stacksize;
}

//取栈顶元素
int GetTop(SqStack S)
{
return S->Top->data;
}