【C语言 数据结构自学笔记】——栈

第四节 栈

  • 栈可以说是一种特别的单链表,它最显著的特征是后进先出,既最先进入栈的元素最后出栈,在各个游戏的地图页面经常能够看到栈的应用。

那么,接下来就进入实战啦,Qwq(

  1. 和之前一样,想要使用某一个数据结构的时候,首先要完成结构体的创建。
//
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;
}
  1. 定义想要使用的函数:
// 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
  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值