bangbang控制c语言代码大全,算法2-3~2-6:Big Bang-题解(C语言代码)

给出了一些参考代码,思路也挺清晰的。数据结构或许还可以改进。

### **注意:在使用指针之前先判断是否为空指针。**

````c

typedef struct _Node//定义一个数据结构

{

int sign;//序号

char *name;//使用时根据名字大小动态分配内存

struct _Node* parent;//指向父节点

struct _Node* next;//指向下一个节点

}Node;

Node* Head = NULL; //定义一个全局指针,该指针没有数据,指向第一个有数据的节点

char com[7];//命令

char name[30];//名字

//处理每一条命令,ctrl+z退出程序

while(1)

{

if(scanf("%s",com) == EOF)

break;

if(strcmp(com,"insert") == 0)//比较命令

{

int num;

scanf("%d",&num);//获取序号

scanf("%s",name);

insert(name, num);

}

//其他的命令类似。

}

//插入

void insert(char *name,int number)

{

Node* tmp;

if(Head == NULL)

{

Head = (Node*)malloc(sizeof(Node));

Head->sign = 0;

Head->name = NULL;

Head->parent = NULL;

Head->next = NULL;

//printf("Head = %p\n",Head);

}

tmp = Head;//指向Head内存地址

//printf("tmp = %p\n",tmp);

//新的节点

Node* node = (Node*)malloc(sizeof(Node));

//给name 分配内存,strlen(name) + 1,c风格字符串尾部补'\0'

node->name = (char*)malloc(sizeof(char) * strlen(name) + 1);

node->sign = number;

strcpy(node->name, name);

node->parent = NULL;

node->next = NULL;

while(1)

{

if(tmp->sign == number )

{

tmp->parent->next = node;

node->parent = tmp->parent;

node->next = tmp;

tmp->parent = node;

//将当前节点还有下一个节点的序号增1.

tmp->sign = number + 1;

while(tmp->next != NULL)

{

tmp = tmp->next;

tmp->sign = tmp->sign + 1;

}

break;//退出循环

}else if(tmp->next == NULL)//没有找到满足的序号

{

node->sign = tmp->sign + 1;//防止给出的序号和实际的数据量不匹配。例:序号3, 数据量 1. 所以,执行这条语句后序号变为 2。

tmp->next = node;

node->parent = tmp;

break;

}

tmp = tmp->next;

}

}

//查找

while(tmp->next != NULL)

{

tmp = tmp->next;//Head节点没有数据,

if(strcmp(tmp->name, name) == 0)

{

return tmp->sign;

}

}

return -1;//没找到

//delete

while(tmp->next != NULL)

{

tmp = tmp->next;//Head节点没有数据,

if(strcmp(tmp->name, name) == 0)

{

if(tmp->next != NULL)

{

tmp->parent->next = tmp->next;

tmp->next->parent = tmp->parent;

Node* tmp2 = tmp;

while(tmp2->next != NULL)//当前节点的下一个节点的序号 -1.

{

tmp2 = tmp2->next;

tmp2->sign = tmp2->sign - 1;

}

}else

{

tmp->parent->next = NULL;

}

tmp->parent = NULL;

tmp->next = NULL;

free(tmp->name);//释放name的内存

free(tmp);//释放节点的内存

return;

}

}

}

````

0.0分

0 人评分

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值