数据结构学习 链式栈的C语言实现

#pragma once

#include <stdio.h>
#include <stdlib.h>

typedef int data_t;
typedef struct node
{
	data_t data;
	struct node* next;

}linknode, *linkstack;

//创建新节点
linkstack linkstack_creat();

//链式栈压栈
int linkstack_push(linkstack p, data_t val);

//出栈
data_t linkstack_pop(linkstack p);

//打印栈
void linkstack_show(linkstack p);

//释放动态开辟空间
int linkstack_free(linkstack* p);

头文件LinkStack.h

#include "LinkStack.h"

linkstack linkstack_creat()
{
	linkstack p;
	p = (linkstack)malloc(sizeof(linknode));
	if (p == NULL)
	{
		printf("Malloc Error.\n");
		return NULL;
	}
	p->data = 0;
	p->next = NULL;

	return p;
}

int linkstack_push(linkstack p, data_t val)
{
 	if (p == NULL)
	{
		printf("Pointer is NULL.\n");
		return -1;
	}
	linkstack newnode = linkstack_creat();
	while (p->next != NULL)
	{
		p = p->next;
	}
	p->next = newnode;
	newnode->data = val;
	return 0;
}

data_t linkstack_pop(linkstack p)
{
	if (p == NULL)
	{
		printf("Pointer is NULL.\n");
		return -1;
	}
	if (p->next == NULL)
	{
		printf("Stack is empty.\n");
		return -1;
	}
	data_t val;
	linkstack temp;
	temp = p;
	while (temp->next != NULL)
	{
		temp = temp->next;
	}
	val = temp->data;
	return val;
}

void linkstack_show(linkstack p)
{
	if (p == NULL)
	{
		printf("Pointer is NULL.\n");
		return;
	}
	if (p->next == NULL)
	{
		printf("Stack is empty.\n");
		return;
	}
	int i = 0;
	linkstack temp = p;

	//检测链表长度,以便从栈顶开始打印
	while (temp->next != NULL)
	{
		temp = temp->next;
		i++;
	}

	while (i > 0)
	{
		temp = p;
		for (size_t j = i; j > 0; j--)
		{
			temp = temp->next;

		}
		printf("%d\t%p\n", temp->data, &(temp->data));
		i--;
	}
}

int linkstack_free(linkstack* p)
{
	if (p == NULL)
	{
		printf("Pointer is NULL.\n");
		return -1;
	}
	linkstack temp;
	while (*p != NULL)
	{
		temp = *p;
		*p = (*p)->next;
		free(temp);
	}
	return 0;
}

函数实现LinkStack.c

#include "LinkStack.h"

int main()
{
	linkstack p;
	p = linkstack_creat();
    //test
	for (int i = 1; i < 6; i++)
	{
		linkstack_push(p, i);

	}
	linkstack_show(p);

	linkstack_pop(p);

	linkstack_show(p);

	linkstack_free(&p);
    //
	return 0;
}

测试函数test.c

        释放动态空间时也可以不使用二级指针,将linkstack_free定义为返回值为结构体指针linkstack类型的函数,在调用函数时使用头结点指针接收返回值NULL即可。

//LinkStack.h
linkstack linkstack_free(linkstack p);

//test.c
p = linkstack_free(p);

//LinkStack.c
linkstack linkstack_free(linkstack p)
{
	if (p == NULL)
	{
		printf("Pointer is NULL.\n");
		return -1;
	}
	linkstack temp;
	while (p != NULL)
	{
		temp = p;
		p = p->next;
		free(temp);
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值