各位带佬,麻烦帮我看一下代码。代码在进行插入元素操作时没有反应。我规定的在第一个结点之前为0位置,1结点之后为1位置,以此类推。在进行非零位置结点的插入时,代码一直不执行。闷头想了半天也没想出个所以然😭希望各位带佬帮我解答一下😄
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
//结点定义
typedef struct _node
{
int value;//数据域
struct _node *next;//指针域
} Node;
//为了使用函数,将链表的输入输出插入删除模块化
//向函数传进去的参数要为*head(所有的操作都要从链表的头开始——输入、输出、插入、删除)
//定义一个结构用来存放*head(这样就可以通过访问该结构的地址来访问*head)
typedef struct _list
{
Node *head;
} List;
//链表的输入
void listCreate(List *list);
//链表的打印
void listPrint(List *list);
//链表元素的查找
void listSearch(List *list);
//结点的插入
void listInsert(List *list);
int main(int argc, char const *argv[])
{
List list;
list.head = NULL;
listCreate(&list);
listPrint(&list);
listSearch(&list);
listInsert(&list);
listPrint(&list);
system("pause");
return 0;
}
void listCreate(List *list)
{
int number;
do
{
printf("请输入元素:");
scanf("%d", &number);
if (number != -1)
{
//创造结点
Node *p = (Node *)malloc(sizeof(Node));
p->value = number; //数值域赋值
p->next = NULL; //指针域赋值
Node *last;
last = list->head;
//结点连接
if (last != NULL)
{
while (last->next != NULL)
{
last = last->next; //移动last
}
last->next = p;
}
else
{
list->head = p; //移动head
}
}
} while (number != -1);
}
void listPrint(List *list)
{
Node *print;
print = list->head;
printf("当前链表元素为:\n");
while (print != NULL)
{
printf("%d\t", print->value);
print = print->next;
}
printf("\n");
}
void listSearch(List *list)
{
Node *searchNumber;
int cnt = 1;//存储位置的变量
printf("请输入要查询的元素:\n");
scanf("%d", &searchNumber->value);
searchNumber->next = NULL;
Node *search;
//遍历链表
for (search = list->head; search != NULL; search = search->next, cnt++)
{
if (search->value == searchNumber->value)
{
printf("找到了,该元素在第%d个结点\n", cnt);
break;
}
}
}
void listInsert(List *list)
{
int position;//插入位置
int cnt = 1; //位置判断变量
char flag;//判断变量
Node *search, *searchfront;
printf("是否插入结点:\n");
getchar();//清除缓冲区
scanf("%c", &flag);
while (flag != 'N')
{
printf("请输入在哪里插入结点:\n");
scanf("%d", &position);
//创建一个结点并初始化
Node *newNode = (Node *)malloc(sizeof(Node));
printf("输入插入元素:\n");
scanf("%d", &newNode->value);
newNode->next = NULL;
//查找要插入的位置并插入
while(cnt != position)
{
if (position != 0)
{
for (search = list->head; cnt != position; searchfront = search, search = search->next)
{
//如果查找到要插入的位置
if (cnt == position)
{
//连接操作
searchfront->next = newNode;
newNode->next = search;
printf("已插入该节点\n");
break;
}
cnt++;
}
}
else
{
newNode->next = list->head;
list->head = newNode;//移动头指针
printf("已插入该节点\n");
break;//跳出循环
}
}
printf("是否插入结点:\n");
getchar();//清除缓冲区
scanf("%c", &flag);
}
}