栈的两种实现方式

1.数组方式

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


//先进后出,数组实现的栈有大小限制,会栈溢出
//可配合循环实现递归
#define N 100
struct stack {
	int top;
	int data[N];
};

struct stack mystack = { -1,{0} };

int isempty()//1空,0非空
{
	if (mystack.top == -1)
	{
		return 1;
	}
	else
	{
		return 0;
	}
}

void setempty()
{
	mystack.top = -1;
}

int push(int data)//压入一个数据.成功返回1失败返回0
{
	if (mystack.top + 1 <= N - 1)//没有发生栈溢出。从a0-an-1存数据
	{
		mystack.data[mystack.top+1] = data;//数组上升一个,接收新的数据
		mystack.top += 1;//下标移动1次
		return 1;
	}
	else
	{
		return 0;
	}
}

int pop()//取数据
{
	if (isempty() == 0)//1空,0非空
	{
		mystack.top -= 1;
		return mystack.data[mystack.top + 1];
	}
	else
	{
		return -1;
	}
}

2.链表方式

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

#define datatype int

struct stacknode {
	int num;
	datatype data;
	struct stacknode* next;
};

typedef struct stacknode StackNode;


StackNode* init(StackNode* phead)
{
	return NULL;
}
StackNode* push(StackNode* phead, int num, datatype data)//就是尾部插入节点
{
	StackNode* pnewnode = malloc(sizeof(StackNode));
	pnewnode->num = num;
	pnewnode->data = data;
	pnewnode->next = NULL;
	if (phead == NULL)
	{
		phead->next = pnewnode;
	}
	else
	{
		StackNode* p = phead;
		while (p->next != NULL)
		{
			p = p->next;
		}
		p->next=pnewnode;
	}
	return phead;
}


StackNode* pop(StackNode* phead, StackNode* outdata)
{
	if (phead==NULL)
	{
		return NULL;
	}
	else if (phead->next==NULL)//只有1个节点
	{
		outdata->data = phead->data;
		outdata->num = phead->num;
		free(phead);
		phead = NULL;
		return phead;
	}
	else
	{
		StackNode* p = phead;
		while (p->next->next != NULL)
		{
			p = p->next;
		}
		outdata->data = phead->next->data;
		outdata->num = phead->next->num;
		free(p->next);
		p->next = NULL;
		return phead;
	}

}

StackNode* freeall(StackNode* phead)//释放内存
{
	if (phead==NULL)
	{
		return;
	}
	else
	{
		StackNode* p1, * p2;
		p1 = phead;
		while (p1->next != NULL)
		{
			p2 = p1->next;//保存下一个节点
			p1->next = p2->next;
			free(p2);
		}
		free(phead);
		return NULL;
	}
}

void test()
{
	StackNode* phead=NULL;
	phead=init(phead);
	phead = push(phead, 1, 1);
	phead = push(phead, 2, 10);
	phead = push(phead, 3, 11);
	
	StackNode* out = malloc(sizeof(StackNode));
	while (phead->next != NULL)
	{
		pop(phead, out);
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值