您的位置:首页 > 编程语言 > C语言/C++

用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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: