栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

栈(C语言)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

栈(C语言)

1、使用数组实现一个栈
#include 

int a[FILENAME_MAX];
int top = -1;
void Pop();
void Push(int x);
int Top();
void Print();
int main()
{
	Push(3);
	Push(5);
	Push(10);
	Print();
	Pop();
	Print();
}
void Push(int x)
{
	if (top == FILENAME_MAX - 1)
	{
		printf_s("Error:Overflow array!");
		return;
	}
		
	a[++top] = x;//top++;a[top]=x;
}
void Pop()
{
	if (top==-1)
	{
		printf_s("Error:Empty array!");
		return;
	}
	top--;
}
int Top()
{
	return a[top];
}
void Print()
{
	if (top == -1)
	{
		printf_s("Error:Empty Array!");
		return;
	}
	printf_s("Stack is:");
	for (int i = 0; i < top; i++)
	{
		printf_s("%d ", a[i]);
	}
	printf_s("n");
}

2、使用链表实现一个栈 
#include 
struct Node
{
	int data;
	struct Node* next;
};
struct Node* top;
void Push(int x);
void Pop();
void Print();
int main()
{
	Push(3);
	Push(5);
	Push(7);
	Print();
	Pop();
	Print();
}
void Push(int x)
{
	struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
	temp->data = x;
	temp->next = top;
	top = temp;
}
void Pop()
{
	if (top == NULL) return;
	struct Node* temp = top;
	top = top->next;
	temp->next = NULL;
	free(temp);
}
void Print()
{
	if (top == NULL) return;
	struct Node* temp = top;
	printf_s("Stack is:");
	while (temp!=NULL)
	{
		printf_s("%d ", temp->data);
		temp = temp->next;
	}
	printf_s("n");
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/348057.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号