用c语言实现链栈 (带头结点)

这篇博客介绍了如何使用C语言创建和操作链栈,包括创建空栈、插入节点(入栈)、取出栈顶元素(top)、删除栈顶元素(出栈)、打印栈中元素、计算栈中元素数量以及检查栈是否为空等基本操作。示例代码展示了完整的实现过程。
摘要由CSDN通过智能技术生成
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <stdlib.h>
using namespace std;
typedef struct Node
{
   int element;
   struct Node* next;
}Node;
///创建空的栈
Node *creatstack()
{
  Node *s = (Node *)malloc(sizeof(Node));
  if(!s) return NULL;
  s ->next = NULL;
  return s;
}
///创建空的节点
Node *creatNode(int item)
{
	Node *tmp = (Node*)malloc(sizeof(Node));
	if(!tmp) return NULL;
	tmp->next = NULL;
	tmp->element = item;
	return tmp;
}
///插入节点,入栈,链表的头插入节点元素
void push(Node *s,int item)
{
	Node *tmp = creatNode(item);
    if(!tmp) printf("无法申请内存");
	else
	{
		tmp->next = s->next;
		s->next = tmp;
	}
}
///取出栈顶元素
int top(Node* s)
{
	return s->next->element;
}
///出栈
void pop(Node* s)
{
	Node *tmp = s->next;
	s->next = s->next->next;
	free(tmp);
}
///打印栈中元素,越早进去ÿ
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值