背包(bag)

/*背包(bag)*/
/*链表+栈实现*/
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>

typedef int Item;
typedef struct bag_type* Bag;

struct node                   /*背包元素*/
{
	Item val;
	struct node* next;
};
struct bag_type             /*背包首元素指针*/
{
	struct node* first;
	int quantity;
};


/**************************************************
* 辅助函数:
*       1.错误处理
*       2.判断背包是否为空
*
****************************************************/

//1.错误处理
static void terminate(const char* message)
{
	printf("%s\n", message);
	exit(EXIT_FAILURE);
}

//2.判断背包是否为空
bool is_empty(int q)
{
	if (q == 0)
	{
		return true;
	}
	else
	{
		return false;
	}
}

/************************************************
* 栈的操作:
*       1.构建新背包
*       2.进入背包
*       3.搜索
*       4.背包大小
*
**************************************************/

//1.构建新背包
Bag create(void)
{
	Bag b = malloc(sizeof(struct bag_type));
	if (b == NULL)
	{
		printf("Error: malloc failed in create.\n");
		exit(EXIT_FAILURE);
	}

	b->first = NULL;
	b->quantity = 0;
	return b;                      /*返回背包首指针*/
}

//2.进入背包
void add(Bag b, Item n)
{
	struct node* new_node = malloc(sizeof(struct node));
	if (new_node == NULL)
	{
		terminate("Error: malloc failed in push.");
	}

	new_node->val = n;
	new_node->next = b->first;
	b->first = new_node;
	(b->quantity)++;
}

//3.搜索
struct node* search(Bag b, Item n)
{
	struct node* cur;
	int i;

	for (cur = b->first, i = b->quantity;
		i > 0;
		cur = cur->next, i--)
	{
		if (cur->val == n)
		{
			return cur;
		}
	}

	return NULL;                      /*n没有找到*/
}

//4.背包大小
int size(Bag b)
{
	return b->quantity;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值