C语言 实现栈

#include <stdio.h>
#include <stdlib.h>

typedef struct Node
{
    /* data */
    int data;
    struct Node* next;

} Node;

Node* initStack();

void push(Node* statck, int value);
int pop(Node* statck);

length(Node* list);
void printList(Node* list);

int main(int argc, char const* argv[]) {
	Node* statck = initStack();
	push(statck, 10);
	push(statck, 11);
	push(statck, 12);
	push(statck, 13);
	push(statck, 14);
	printList(statck);
	int poped = pop(statck);
	printList(statck);
	printf("pop数据 = %d\n", poped);
	int poped2 = pop(statck);
	printList(statck);
	printf("pop数据 = %d\n", poped2);
	int poped3 = pop(statck);
	printList(statck);
	printf("pop数据 = %d\n", poped3);
	return 0;
}

Node* initStack() {
	Node* statck = (Node*)malloc(sizeof(Node));
	statck->data = 0;
	statck->next = NULL;
	return statck;
}

void push(Node* statck, int value) {
	Node* node = (Node*)malloc(sizeof(Node));
	node->data = value;
	node->next = statck->next;
	statck->next = node;
	statck->data++;
}

int pop(Node* statck) {
	Node* node = statck->next;
	
	statck->data--;
	statck->next = statck->next->next;
	return node->data;
}

// 工具方法
int length(Node* list) {
    return list->data;
}

void printList(Node* list) {
    if (list->data == 0)
    {
        printf("List is empty");
        return;
    }
    list = list->next;
    printf("[ ");
    
    while (list->next)
    {
        printf("%d,", list->data);
        list = list->next;
    }
    printf("%d", list->data);
    printf(" ]\n");
}

自己备份一下

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值