通过链式存储来实现对栈进行的各种操作。
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define OVERFLOW 1
typedef struct Node
{
int data;
struct Node *next;
}Node;
typedef struct LinkStack
{
Node *top;//栈顶指针
int count;//记录栈元素个数
}LinkStack;
//初始化
void InitLinkStack(LinkStack *S)
{
S->top = (Node*)malloc(sizeof(Node));
S->top->next = NULL;
S->count = 0;
}
//栈顶元素
int GetTop(LinkStack *S)
{
int n;
n= S->top->data;
printf("栈顶元素是%d\n",n);
return 1;
}
//压栈
void Push(LinkStack *S,int n)
{
Node *N;
N = (Node*)malloc(sizeof(Node));
N->data = n;
N->next = S->top;
S->top=N ;
S->count ++;
}
//弹栈
void Pop(LinkStack *S)
{
int n;
Node *N;
if(!(S->top))
exit(OVERFLOW);
N = S->top;
n=N->data;
printf("%d",n);
S->count --;
if( S->count == 0)
{
free(S->top);
S->top = NULL;
}
else
{
N = S->top->next;
free(S->top);
S->top = N;
}
}
//将十进制数转换为八进制
void conversion(int n)
{
LinkStack *S;
InitLinkStack(S);
while(n)
{
Push(S,n%8);
n=n/8;
}
while(S->count!=0)
{
Pop(S);
}
}
int main()
{
LinkStack *S;
int i,k,n;
S=(LinkStack*)malloc(sizeof(LinkStack));
InitLinkStack(S);
int quit=1;
while(quit==1)
{
printf("1.Push 2.Pop 3.getTop 4.conversion\n");
scanf("%d",&k);
getchar();
switch(k)
{
case 1:
printf("Push number \n");
scanf("%d",&i);
Push(S,i);
break;
case 2:
printf("Pop number is ");
Pop(S);
printf("\n");
break;
case 3:
GetTop(S);
break;
case 4:
printf("Conversion number is ");
scanf("%d",&n);
conversion(n);
break;
}
}
return 0;
}