用c语言实现链栈 (带头结点)
2017-08-09 22:04
288 查看
#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); } ///打印栈中元素,越早进去,越晚出来 void print(Node* s) { Node *p = s->next; while(p) { printf("%d ",p->element); p = p->next; } printf("\n"); } ///求栈中元素的多少 int sizestack(Node *s) { Node *p = s->next; int cnt = 0; while(p) { cnt ++; p = p->next; } return cnt; } ///检验栈是否为空 bool isempty(Node* s) { return s->next==NULL; } int main() { Node *stack = creatstack(); push(stack,5); //push(stack,6); //push(stack,7); //push(stack,8); //push(stack,9); //push(stack,10); print(stack); printf("%d\n",top(stack)); pop(stack); print(stack); printf("%d\n",sizestack(stack)); if(isempty(stack)) printf("emtpy!\n"); return 0; }
相关文章推荐
- 双指针不带头结点的链栈的实现(C语言)
- 双指针不带头结点的链栈的实现(C语言)
- C语言实现双向非循环链表(带头结点尾结点)的节点插入
- [置顶] 不带头结点的 单链表的各种操作实现c语言
- C语言实现单链表的逆序打印(带头结点)
- c语言实现--带头结点单链表操作
- C语言实现非循环双链表节点的删除(不带头结点)
- c语言实现--不带头结点的单链表操作
- C语言实现单链表(带头结点)的基本操作(创建,头插法,尾插法,删除结点,打印链表)
- C语言实现单链表节点的删除(带头结点)
- C语言实现单链表的节点插入(带头结点)
- C语言实现非循环双链表节点的删除(带头结点尾结点)
- 链表中每个结点的data域存放一个二进制位。并在此链表上实现对二进制数加1的运算。 用C语言编写 用以存放输入的二进制数 建立 一个带头结点的线性链表
- C语言实现双向非循环链表(不带头结点)的清空
- C语言实现单链表(带头结点)的基本操作
- C语言实现单链表节点的删除(带头结点)
- 带头结点的链队列实现(C语言)
- 数据结构模版----单链表SimpleLinkList[带头结点&&面向对象设计思想](C语言实现)
- C语言实现双向非循环链表(带头结点尾结点)的基本操作
- 数据结构模版----单链表SimpleLinkList[带头结点](C语言实现)