头文件
struct Node{
int data;
struct Node *Next;
};
typedef struct Node *PtrToNode;
typedef PtrToNode Stack;
int IsEmpty(Stack S);
void MakeEmpty(Stack S);
Stack CreateStack(void);
void Push(int X,Stack S);
int Top(Stack S);
void Pop(Stack S);
#include
#include "stack.h"
#include
int IsEmpty(Stack S)
{
return S->Next == NULL;
}
void MakeEmpty(Stack S)
{
if(S == NULL)
printf("must");
else
while(!IsEmpty(S))
Pop(S);
}
Stack CreateStack(void)
{
Stack S;
S = malloc(sizeof(struct Node));
if(S == NULL)
printf("Out of range");
S->Next = NULL;
MakeEmpty(S);
return S;
}
void Push(int X,Stack S)
{
PtrToNode TmpCell;
TmpCell = malloc(sizeof(struct Node));
if(TmpCell == NULL)
printf("Out of range");
else
{
TmpCell->data = X;
TmpCell->Next = S->Next;
S->Next = TmpCell;
}
}
int Top(Stack S)
{
if(!IsEmpty(S))
return S->Next->data;
printf("Out of range");
return 0;
}
void Pop(Stack S)
{
PtrToNode FirstCell;
if(IsEmpty(S))
printf("Out of range");
else
{
FirstCell = S->Next;
S->Next = S->Next->Next;
free(FirstCell);
}
}
这个基本上是照书一点一点打的,我不太懂关于Top操作
为什么知道了指向栈底部的指针S就可以用
S->Next->data 得知栈顶元素,这个我自己实验过是对的。
因为假如这个栈是由3个链表连起来的,S->Next->data应该得到的是第二个链表里面的元素啊。
S->Next->Next->data才是栈顶的元素。
我也曾怀疑过是不是Push操作改变了指针S指向的地方。。但打印出的S的地址都是一样啊。
顺便可以问一下,假如我要打印某个地址 是应该 用 %d 吗,我的文本编辑器总报warning。。
提一下我的文本编辑器是geany 编译器是gcc Linux下
我是小白。。求指教啊啊啊啊。。google后也不明白。。卡了好几天了
希望有人可以帮我一下..