C语言实现链式栈

6 篇文章 0 订阅

https://blog.csdn.net/HZPHYT/article/details/81369022

http://data.biancheng.net/view/171.html

#include<stdio.h>

#include <string.h>

#include<assert.h>

#include <math.h>

#include <stdlib.h>

 

#define bool int

#define true (1U)

#define false (0U)

/* 695. 岛屿的最大面积 */

#define max(a,b) ((a)>(b)?(a):(b))

#define min(a,b) ((a)<(b)?(a):(b))

 

typedef struct node{

int data;

struct node *next;

}Node, *pNode;

 

typedef struct {

pNode top;

int count;

}LinkStack, *pLinkStack;

 

void initStack(LinkStack *S)

{

if(S == NULL){

return;

}

S->count = 0;

S->top = NULL;

}

 

/* 入栈操作,链表的头作为栈顶元素,链表的尾作为栈底元素 */

void pushStack(LinkStack *S, int val)

{

if(S == NULL){

return;

}

Node *p = (Node *)malloc(sizeof(Node));

if(p == NULL){

return;

}

p->data = val;

/* 新节点与头节点的关系 */

p->next = S->top;

/* 新的栈顶元素是p */

S->top=p;

/* 栈中数据数目++ */

S->count++;

}

 

void popStack(LinkStack *S, int *val)

{

if((S == NULL) || (val == NULL)){

return;

}

Node *pNext = NULL;

Node *pTop = S->top;

*val = S->top->data;

pNext = S->top->next;

S->top = pNext;

S->count--;

free(pTop);

}

 

int isStackEmpty(LinkStack *S)

{

if (S == NULL) {

return 1;

}

if (S->top == NULL) {

return 1;

} else {

return 0;

}

}

 

int topNodeData(LinkStack *S)

{

return S->top->data;

}

 

int stackLenth(LinkStack *S)

{

return S->count;

}

 

int main(void)

{

int len = 0;

int top = 0;

LinkStack S;

initStack(&S);

pushStack(&S, 1);

pushStack(&S, 3);

pushStack(&S, 5);

pushStack(&S, 7);

top = topNodeData(&S);

len = stackLenth(&S);

printf("topData = %d, len = %d\n", top, len);

while(isStackEmpty(&S) != 1){

popStack(&S, &top);

printf("delete top data is %d\n",top);

}

while(1);

return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值