您的位置:首页 > 其它

栈的链表实现

2015-09-23 11:27 232 查看
声明 stack.h:

#ifndef STACK_H_INCLUDED
#define STACK_H_INCLUDED
struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode Stack;

int IsEmpty(Stack S);
Stack CreateStack(void);
void DisposeStack(Stack S);
void MakeEmpty(Stack S);
void Push(int X, Stack S);
int Top(Stack S);
void Pop(Stack S);

#endif // STACK_H_INCLUDED


实现 implementation.c:

#include<stdio.h>
#include "stack.h"
struct Node{
int Num;
PtrToNode Next;
};

int IsEmpty(Stack S) {
return S->Next == NULL;
}

Stack CreateStack(void) {
Stack S;
S = malloc(sizeof(struct Node));
if(S == NULL){
printf("Error!");
}
S->Next = NULL;
MakeEmpty(S);
return S;
}

void MakeEmpty(Stack S) {
if(S == NULL)
printf("Must use CreateStack() frist");
while(!IsEmpty(S)){
Pop(S);
}
}

void Push(int X, Stack S) {
PtrToNode TmpCell;
TmpCell = malloc(sizeof(struct Node));
if(TmpCell == NULL)
printf("Out of space!");
else{
TmpCell->Next = S->Next;
TmpCell->Num = X;
S->Next = TmpCell;
}
}

void Pop(Stack S) {
PtrToNode FirstCell;
if(IsEmpty(S))
printf("Empty Stack!");
else{
FirstCell = S->Next;
S->Next = S->Next->Next;
free(FirstCell);
}
}

int Top(Stack S) {
if(!IsEmpty(S)){
return S->Next->Num;
} else {
printf("Empty Stack");
}
}


测试 main.c:

#include <stdio.h>
#include <stdlib.h>
#include "stack.h"

int main()
{
Stack S;
S = CreateStack();
Push(1, S);
Push(2, S);
Push(3, S);
printf("%d ", Top(S));
Pop(S);
printf("%d",Top(S));
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: