表头S为指针,指向一个结构体,S->next表示S指向的结构体中的结构的next域,这个next存储的是栈顶的地址,所以S->next表示栈顶地址,所以S->next->element表示栈顶的元素中的值。
具体代码如下:
#ifndef MYSTACK_H_
#define MYSTACK_H_
#include <stdio.h>
#include <stdbool.h>
#include <malloc.h>
struct Node;
typedef struct Node * Stack; //用于声明指向表头的指针
typedef struct Node * PtrToNode; //用于声明指向结构体(节点)的指针
typedef int ElementType;
struct Node
{
ElementType element;
PtrToNode next;//前一个节点(元素)地址
};
//函数声明
Stack InitStack(void);//创建一个空栈,返回表头地址
bool IsEmpty(Stack S); //判断是否为空 空返回true
Stack Pop(Stack S);// 出栈 返回新栈顶地址
void ClearStack(Stack S); //清空栈 变为空栈
int StackLength(Stack S); //返回栈中元素数目
ElementType GetTop(Stack S);//返回栈顶的值
Stack Push(ElementType E, Stack S);// 入栈 返回新栈顶地址
//函数实现
Stack InitStack(void)
{
Stack tempNode;
tempNode = (PtrToNode)malloc(sizeof(struct Node));
if(tempNode == NULL)
printf("Out of space!\n");
tempNode -> next = NULL;
return tempNode;
}
bool IsEmpty(Stack S)
{
return S -> next == NULL;
}
Stack Pop(Stack S)
{
PtrToNode tempNode;
if(IsEmpty(S)){
printf("Stack is empty\n");
return S;
}
else{
tempNode = S -> next;
S -> next = S -> next -> next; //S为表头地址,表头的next存的是栈顶的地址
free(tempNode); //栈底元素的next为NULL 所以在删除最后一个元素后
return S; //S的next才为NULL
}
}
void ClearStack(Stack S)
{
while(IsEmpty(S) != true)
S = Pop(S);
}
int StackLength(Stack S)
{
int sum = 0;
while(IsEmpty(S) != true){
S -> next = S -> next -> next;
sum ++;
}
return sum;
}
ElementType GetTop(Stack S)
{
if(IsEmpty(S)){
printf("Stack is empty\n");
return 0; //返回值防止编译器报错
}
else
return S -> next -> element;
}
Stack Push(ElementType E, Stack S)
{
PtrToNode tempNode;
tempNode = (PtrToNode)malloc(sizeof(struct Node));
if(tempNode == NULL){
printf("Out Of Space!\n");
return tempNode;
}
else{
tempNode -> next = S -> next;
tempNode -> element = E;
S -> next = tempNode;
return S;
}
}
#endif