第四节 栈
- 栈可以说是一种特别的单链表,它最显著的特征是后进先出,既最先进入栈的元素最后出栈,在各个游戏的地图页面经常能够看到栈的应用。
那么,接下来就进入实战啦,Qwq(
- 和之前一样,想要使用某一个数据结构的时候,首先要完成结构体的创建。
//
typedef struct Node {
int data;
struct Node* next;
}Node;
//
Node* initStack(void){
Node* S = (Node*)malloc(sizeof(Node));
S ->data = 0;
S ->next = NULL;
return S;
}
- 定义想要使用的函数:
// if the stack is Empty return "-1" , else return 1;
// if the "mode" is "1" ,the function is the only judge,else if the stack is no't empty return the data from the top of the snack
int JNEmpty(Node* S , int mode){
if (mode){
if(S ->next == NULL || S ->data == 0){
return -1;//Empty
}
else{
return 1;//NEmpty
}
}
else{
return S ->next->data;
}
}
//
int pop(Node* S){
Node* node = (Node*)malloc(sizeof(Node));
node = S ->next;
if(JNEmpty(S,1)){
S ->next = node ->next;
S ->data--;
return node ->data;
}
else{
printf("ERROR! The Stack is Empty!");
return -1;
}
}
//
void push(Node* S ,int data){
Node* node = (Node*)malloc(sizeof(Node));
node ->data = data;
S ->data++;
node ->next = S ->next;
S ->next = node;
}
//
void PrintLong(Node* S){
printf("The long of Stack is %d\n",S ->data);
}
//
void PrintSnack(Node* S){
int temp;
temp = S ->data;
while(temp){
temp--;
S = S ->next;
printf("%d->",S->data);
}
printf("NULL\n");
}
编写主函数,验证一下吧!
int main()
{
Node* S = initStack();
push(S,1);
push(S,2);
push(S,3);
PrintSnack(S);
PrintLong(S);
pop(S);
PrintSnack(S);
PrintLong(S);
}
运行结果:
3->2->1->NULL
The long of Stack is 3
2->1->NULL
The long of Stack is 2