C语言 数据结构之 栈

目录

什么是栈及其特点

初始化栈

判断栈空

出栈

入栈

打印

用于检验上述函数效果的主函数

完整源代码


什么是栈及其特点

栈是一种特殊的线性表,它只能在一端进行存取操作,导致其元素有先进后出的特点

栈的特点是先进后出(进栈和出栈的顺序相反,先进去的后面出来)

栈的应用场景:(1)表达式的值

                         (2)解决一些递归问题

                         (3)计算进制转换

入栈和出栈操作可以转化为结点的头插(先进行的头插的位置靠后)和删除(并且要返回第一个结点的值)

初始化栈


typedef struct Stack {
    int data;
    struct Stack* next;
}Stack;

//初始化(含头结点,其data表示栈内结点的个数)
Stack* initStack() {
    Stack* S = (Stack*)malloc(sizeof(Stack));
    S->data = 0;
    S->next = NULL;
    return S;
}

判断栈空

int isEmpty(Stack* S) {
    if (S->data == 0 || S->next == NULL)
        return 1;
    else
        return 0;
}

出栈


int pop(Stack* S) {
    if (isEmpty(S))
        return -1;
    else
    {    
        Stack* node = S->next;
        int data = node->data;
        S->next = node->next;
        free(node);
        return data;
    }
}

入栈


void push(Stack* S ,int data) {
    Stack* node = (Stack*)malloc(sizeof(Stack));
    node->data = data;
    node->next = S->next;
    S->next = node;
    S->data++;
}

打印

void printStack(Stack* S) {
    Stack* node = S->next;
    while (node) {
        printf("%d->", node->data);
        node = node->next;
    }
    printf("NULL\n");
}

用于检验上述函数效果的主函数

int main() {
    Stack* S = initStack();
    push(S, 1);
    push(S, 2);
    push(S,3 );
    push(S, 4);
    printStack(S);
    printf("current elem = %d\n", pop(S));
    printStack(S);
    printf("current elem = %d\n", pop(S));
    printStack(S);
    return 0;
}


完整源代码

#include "headfile.h"
typedef struct Stack {
	int data;
	struct Stack* next;
}Stack;

//初始化(含头结点,其data表示栈内结点的个数)
Stack* initStack() {
	Stack* S = (Stack*)malloc(sizeof(Stack));
	S->data = 0;
	S->next = NULL;
	return S;
}

int isEmpty(Stack* S) {
	if (S->data == 0 || S->next == NULL)
		return 1;
	else
		return 0;
}

//出栈
int pop(Stack* S) {
	if (isEmpty(S))
		return -1;
	else
	{	
		Stack* node = S->next;
		int data = node->data;
		S->next = node->next;
		free(node);
		return data;
	}
}

//入栈
void push(Stack* S ,int data) {
	Stack* node = (Stack*)malloc(sizeof(Stack));
	node->data = data;
	node->next = S->next;
	S->next = node;
	S->data++;
}

void printStack(Stack* S) {
	Stack* node = S->next;
	while (node) {
		printf("%d->", node->data);
		node = node->next;
	}
	printf("NULL\n");
}

int main() {
	Stack* S = initStack();
	push(S, 1);
	push(S, 2);
	push(S,3 );
	push(S, 4);
	printStack(S);
	printf("current elem = %d\n", pop(S));
	printStack(S);
	printf("current elem = %d\n", pop(S));
	printStack(S);
	return 0;
}


  • 24
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值