马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
心态炸了,这个bug改了一个多小时了,其他没问题,删除函数那里的问题,请大佬看看#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct array
{
int value;
struct array *next;
}ARRAY;
void insert(ARRAY **head);
void delete(ARRAY **head);
void search(ARRAY *head);
void print(ARRAY *head);
int main(void)
{
ARRAY *head = NULL; // 创建头指针
while(1)
{
printf("--------------------------\n");
printf("0.退出程序 1.插入数据\n");
printf("2.删除数据 3.查找元素\n");
printf("--------------------------\n");
int input;
printf("请输入待执行的功能:");
scanf("%d",&input);
if(input < 0 || input > 3)
{
printf("输入有误,请重新输入\n\n");
continue;
}
switch(input)
{
case 0:
printf("成功退出程序,欢迎下次再来\n");
exit(1);
case 1:
insert(&head);
print(head);
break;
case 2:
delete(&head);
print(head);
break;
case 3:
search(head);
break;
}
}
}
// 插入函数
void insert(ARRAY **head)
{
ARRAY *previous = *head;
ARRAY *new;
new = (ARRAY *)malloc(sizeof(ARRAY)); // 开辟新的空间
if(new == NULL)
{
printf("内存分配失败,退出程序\n");
exit(1);
}
printf("请输入一个整数:");
scanf("%d",&new->value);
if(*head != NULL)
{
while(previous->next != NULL)
{
previous = previous->next;
}
previous->next = new;
new->next = NULL;
}
else
{
*head = new;
new->next = NULL;
}
}
// 删除函数
void delete(ARRAY **head)
{
int flag = 0;
ARRAY *current = *head;
ARRAY *previous;
int num;
printf("请输入一个整数:");
scanf("%d",&num);
while(current != NULL)
{
if(current->value == num)
{
printf("找到了,开始删除....");
flag = 1;
previous = current;
free(previous);
}
current = current->next;
}
if(flag == 0)
{
printf("没有找到该数值,删除失败\n"); // 遍历完链表没有找到
}
}
// 查找函数
void search(ARRAY *head)
{
int n = 0, flag = 0;
ARRAY *current = head;
int num;
printf("请输入一个整数:");
scanf("%d",&num);
while(current != NULL)
{
n++;
if(current->value == num) // 有可能存在重复数据,遍历到尾节点
{
flag = 1; // 查找成功,flag = 1
printf("查找成功,是第%d个数\n",n);
}
current = current->next;
}
if(flag == 0)
{
printf("没有找到该数值,查找失败\n"); // 遍历完链表没有找到
}
putchar('\n');
}
// 打印函数
void print(ARRAY *head)
{
ARRAY *current = head;
while(current != NULL)
{
printf("%d ",current->value);
current = current->next;
}
printf("\n\n");
}
本帖最后由 xieglt 于 2020-9-29 08:43 编辑 // 删除函数
void delete1(ARRAY **head)
{
int flag = 0;
ARRAY *current = *head;
ARRAY *previous;
int num;
printf("请输入一个整数:");
scanf("%d",&num);
//如果head是输入的数
if(*head != NULL && (*head)->value == num)
{
*head = (*head)->next;
free(current);
flag = 1;
}
else if(current != NULL)
{
do
{
previous = current;
current = current->next;
if(current == NULL)
{
break;
}
if(current->value == num)
{
previous->next = current->next;
printf("找到了,开始删除....");
flag = 1;
free(current);
break;
}
}while(1);
}
if(flag == 0)
{
printf("没有找到该数值,删除失败\n"); // 遍历完链表没有找到
}
}
|