给出了一些参考代码,思路也挺清晰的。数据结构或许还可以改进。
### **注意:在使用指针之前先判断是否为空指针。**
````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 人评分