/*背包(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;
}