题解 | 栈1

调用函数对栈进行初始化,需传递二级指针;
当然,如果在main函数中对其进行初始化,直接初始化即可。

  • 本篇采用c语言编写,调用函数初始化栈,该栈为链栈,带头结点。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define LEN sizeof(StackNode)//方便malloc函数书写

typedef struct StackNode {//栈的结点结构体
    int data;
    struct StackNode* next;
} StackNode, *LinkStack;

void initStack(LinkStack* h);//初始化栈
void push(LinkStack h);//入栈
void pop(LinkStack h);//出栈
void top(LinkStack h);//获取栈顶元素
int count = 0;//栈的结点个数(不包括头结点)
int main() {
    int n;//操作次数
    LinkStack h;//指向头结点
    initStack(&h);//初始化栈
    //printf("\n请输入操作次数:\t");
    scanf("%d", &n);
    if (n >= 1 && n <= 100000) {
        while (n--) {
            int flag = 0;//判断是否输入错误
            char a[10];
            //printf("\n请输入操作函数:\t");
            scanf("%s", a);
            if (strncmp(a, "push", 4) == 0) {
                push(h);
                flag = 1;
            }
            if (strncmp(a, "pop", 3) == 0) {
                pop(h);
                flag = 1;
            }
            if (strncmp(a, "top", 3) == 0) {
                top(h);
                flag = 1;
            }
            if (flag == 0) {
                printf("输入错误。\n");
            }
        }
    } else {//n输入错误
        printf("error\n");
    }
    return 0;
}

void initStack(LinkStack* h) {//初始化栈
    (*h) = (LinkStack)malloc(LEN);
    (*h)->next = NULL;
}
void push(LinkStack h) {//入栈
    StackNode* p;
    int x;
    //printf("\n请输入入栈x的值:\t");
    scanf("%d", &x);
    p = (StackNode*)malloc(LEN);
    p->data = x;
    p->next = h->next;
    h->next = p;
    count++;
}

void pop(LinkStack h) {//出栈
    if (count == 0) {
        printf("error\n");
        return ;
    }
    StackNode* p;
    p = h->next;
    printf("%d\n", p->data);
    h->next = h->next->next;
    free(p);
    count--;
}

void top(LinkStack h) {//获取栈顶元素
    if (count == 0) {
        printf("error\n");
        return ;
    }
    printf("%d\n", h->next->data);
}
全部评论

相关推荐

自由水:笑死了,敢这么面试不敢让别人说
点赞 评论 收藏
分享
06-07 17:17
嘉兴学院 教师
心爱的idea:你孩
点赞 评论 收藏
分享
测试糕手手:社会第一课,随便吹牛逼,直接说四个月,别老实。老实人只会被欺负
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务