加入收藏 | 设为首页 | 会员中心 | 我要投稿 52站长网 (https://www.52zhanzhang.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

【数据结构】(四)栈之链式栈

发布时间:2022-08-25 20:11:26 所属栏目:PHP教程 来源:
导读: 栈之链式栈 一、链式栈1.何为链式栈?逻辑结构:栈存储结构:链式存储 2.链式栈声明(linkstack.h)3.链式栈基本运算(linkstack.c)(1)创建栈:

一、链式栈

1.何为链式栈?

逻辑结构:栈

链接: 顺序栈中有介绍

存储结构:链式存储

链接: 单链表中有介绍
在这里插入图片描述

2.链式栈声明(linkstack.h)

typedef int data_t;typedef struct node {	data_t data;	struct node *next;}listnode, *linkstack;linkstack stack_create();int stack_push(linkstack s, data_t value);data_t stack_pop(linkstack s);int stack_empty(linkstack s);data_t stack_top(linkstack s);linkstack stack_free(linkstack s);

3.链式栈基本运算(linkstack.c)

(1)创建栈:stack_create()

linkstack stack_create() {	linkstack s;	s = (linkstack)malloc(sizeof(listnode));	if (s == NULL) {		printf("malloc failed/n");		return NULL;	}	s->data = 0;	s->next = NULL;	return s;}

(2)入栈:stack_push(s, value)

int stack_push(linkstack s, data_t value) {	linkstack p;	if (s == NULL) {		printf("s is NULL/n");		return -1;	}	p = (linkstack)malloc(sizeof(listnode));	if (p == NULL) {		printf("malloc failed/n");		return -1;	}	p->data = value;	//p->next = NULL;	p->next = s->next;	s->next = p;	return 0;}

(3)出栈:stack_pop(s)

data_t stack_pop(linkstack s) {	linkstack p;	data_t t;	p = s->next;	s->next = p->next;	t = p->data;	free(p);	p =NULL;	return t;}

(4)判断栈是否空:stack_empty(s)

int stack_empty(linkstack s) {	if (s == NULL) {		printf("s is NULL/n");		return -1;	}	return (s->next == NULL ? 1 : 0);}

(5)返回栈顶值:stack_top(s)

data_t stack_top(linkstack s) {	return (s->next->data);}

(6)销毁栈:stack_free(s)

linkstack stack_free(linkstack s) {	linkstack p;	if (s == NULL) {		printf("s is NULL/n");		return NULL;	}	while (s != NULL) {		p = s;		s = s->next;		printf("free:%d/n", p->data);		free(p);	}	return NULL;}

4.测试函数(test.c)

#include <stdio.h>#include <stdlib.h>#include "linkstack.h"int main(int argc, const char *argv[]){	linkstack s;	s = stack_create();	if (s == NULL) 		return -1;	stack_push(s, 10);	stack_push(s, 20);	stack_push(s, 30);	stack_push(s, 40);#if 0	while (!stack_empty(s)) {		printf("pop:%d/n", stack_pop(s));	}#endif	s = stack_free(s);		return 0;}

(编辑:52站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!