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 人評分
總結
以上是生活随笔為你收集整理的bangbang控制c语言代码大全,算法2-3~2-6:Big Bang-题解(C语言代码)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c语言编程怎么自学网,c语言函数
- 下一篇: 大学生计算机等级考试c 语言程序设计,计