数据结构与算法 栈

栈是一种特殊的线性表 

它只能在一端进行进行操作,因而存取的元素有先进后出的特点

头插法相同 

操作:

1.初始化栈

2.出栈

3.入栈

4.判断栈空

#include<stdio.h>
#include<stdlib.h>
typedef struct Node{
	int data;
	struct Node* next;
}Node;
Node* initstack()
{
	Node* head=(Node*)malloc(sizeof(Node));
	head->next=NULL;
	head->data=0;
} 
int is_empty(Node* head)
{
	if(head->next==NULL||head->data==0)
	{
		return 1;
	}
	else
	{
		return 0;
	}
}
int get_top(Node* head)
{
	if(is_empty(head))
	{
		return -1;
	}
	else
	{
		return head->next->data;
	}
}
int pop(Node* head)
{
	if(is_empty(head))
	{
		return -1;
	}
	else
	{
		Node* node=(Node*)malloc(sizeof(Node));
		node=head->next;
		int data=node->data;
		head->next=node->next;
		free(node);
		return data;
	}
}
void push(Node* head,int data)
{
	Node* node=(Node*)malloc(sizeof(Node));
	node->data=data;
	node->next=head->next;
	head->next=node;
	head->data++;
}
void print_stcak(Node* head)
{
	Node* node=(Node*)malloc(sizeof(Node));
	node=head->next;
	while(node!=NULL){
		printf("%d->",node->data);
		node=node->next;
	}	
	printf("NULL");
}
int main()
{
	Node* s=initstack();
	push(s,1);
	push(s,2);
	push(s,3);
	is_empty(s);
	print_stcak(s);
	printf("\n");
	int i=pop(s);
	printf("top为%d\n",i);
	print_stcak(s);
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值