您的位置:首页 > 其它

2015-11-05 12:05 267 查看
栈链式实现
#include<stdio.h>
#include<stdlib.h>
typedef int ElementType;
struct node {
ElementType  data;
struct node *pNext;
};
typedef struct node Stack;

Stack *CreateStack(void);
void DisposeStack(Stack *L);
int IsEmpty(Stack *L);
Stack *Push(Stack *L, ElementType X);
ElementType PopAndTop(const Stack *L);

Stack *CreateStack(void)
{
Stack *p;
p = (Stack *)malloc(sizeof(Stack));
if (p == NULL)  return NULL;
p->pNext = NULL;
return p;
}
void DisposeStack(Stack *L)
{
Stack *ptemp = L;
if (ptemp != NULL)
{
free(ptemp);
ptemp = ptemp->pNext;
}
}
int IsEmpty(Stack *L)
{
return (L->pNext == NULL);
}
Stack *Push(Stack *L, ElementType X)
{
if (L == NULL) return NULL;
Stack *pNew = (Stack *)malloc(sizeof(Stack));
pNew->data = X;
pNew->pNext = NULL;
if (pNew == NULL) return NULL;

pNew->pNext = L->pNext;
L->pNext = pNew;

return L;
}
ElementType PopAndTop( Stack *L)
{
if (IsEmpty(L) == 1)  return 0;
ElementType num;
num = L->pNext->data;
L->pNext = L->pNext->pNext;
free(L->pNext);
return num;
}

int main(void)
{

return 0;
}

栈顺序实现

#include<stdio.h>
#include<stdlib.h>
typedef int ElementType;
struct node{
int capacity;
int TopOfStack;
ElementType *Array;
};

typedef struct node Stack;

Stack *CreateStack(int maxsize);
void Dispose(Stack *L);

void show(Stack *L);
int IsEmpty(Stack *L);
int IsFull(Stack *L);
void Push(Stack *L, ElementType X);
ElementType PopAndTop(Stack *L);

Stack *CreateStack(int maxsize)
{
Stack *ps;
ps = (Stack *)malloc(sizeof(Stack));
if (ps == NULL) return NULL;
ps->capacity = maxsize;
ps->TopOfStack = -1;
ps->Array = (ElementType*)malloc(sizeof(ElementType)*maxsize);
if (ps->Array == NULL) return NULL;
return ps;
}
void Dispose(Stack *L)
{
if (L == NULL) return;
if (L->Array != NULL) free(L->Array);
free(L);
}
void show(Stack *L)
{
if (L == NULL) return;
int i = L->TopOfStack;
while (i >=0)
{
printf("%d \n", L->Array[i]);
i--;
}
}
int IsEmpty(Stack *L)
{
return (L->TopOfStack == -1);
}
int IsFull(Stack *L)
{
return (L->TopOfStack == L->capacity);
}
void Push(Stack *L, ElementType X)
{
if (IsFull(L) == 1) return ;
L->Array[++(L->TopOfStack)] = X;

}
ElementType PopAndTop(Stack *L)
{
if (IsEmpty(L) == 1) return 0;
return (L->Array[(L->TopOfStack)--]);
}

int main(void)
{
Stack *L = CreateStack(20);
Push(L, 2);
Push(L, 3);
Push(L, 4);
Push(L, 5);
Push(L, 6);
show(L);
printf("\n");
PopAndTop(L);
show(L);
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: