S1E47:单链表3--笔记
本帖最后由 BaysideLizard 于 2023-12-14 12:20 编辑#include <stdio.h>
#include <stdlib.h>
//鱼C论坛——BaysideLizard写于2023年12月14日
struct Numbers
{
int value;
struct Numbers *next;
};
void insertNumbers(struct Numbers **headNumbers,int value);
void printNumbers(struct Numbers *headNumbers);
void delNumbers(struct Numbers **headNumbers,int num);
int main()
{
struct Numbers *headNumbers = NULL;
int num;
printf("单链表插入实验\n");
while(1)
{
printf("请输入一个整数(输入-1表示结束):");
scanf("%d",&num);
if(num == -1)
{
break;
}
insertNumbers(&headNumbers,num);
printNumbers(headNumbers);
}
printf("单链表删除实验\n");
while(1)
{
printf("请输入您要删除的整数(输入-1表示结束):");
scanf("%d",&num);
if(num == -1)
{
break;
}
delNumbers(&headNumbers,num);
printNumbers(headNumbers);
}
return 0;
}
void insertNumbers(struct Numbers **headNumbers,int value)
{
struct Numbers *previous,*current,*nw;
current = *headNumbers;
previous = NULL;
while(current != NULL && current->value < value)
{
previous = current;
current = current -> next;
}
nw = (struct Numbers *)malloc(sizeof(struct Numbers));
if(nw == NULL)
{
printf("内存分配失败!\n");
exit(1);
}
nw->next = current;
nw->value = value;
if(previous == NULL)
{
*headNumbers = nw;
}
else
{
previous->next = nw;
}
}
void printNumbers(struct Numbers *headNumbers)
{
struct Numbers *current;
current = headNumbers;
while(current != NULL)
{
printf("%d ",current->value);
current = current->next;
}
putchar('\n');
}
void delNumbers(struct Numbers **headNumbers,int value)
{
struct Numbers *previous,*current;
current = *headNumbers;
previous = NULL;
while(current != NULL && current->value != value)
{
previous = current;
current = current->next;
}
if(current == NULL)
{
printf("找不到匹配的节点!\n");
return ;
}
else
{
if(previous == NULL)
{
*headNumbers = current->next;
}
else
{
previous->next = current->next;
}
free(current);
}
}
运行结果:
单链表插入实验
请输入一个整数(输入-1表示结束):1
1
请输入一个整数(输入-1表示结束):3
1 3
请输入一个整数(输入-1表示结束):5
1 3 5
请输入一个整数(输入-1表示结束):7
1 3 5 7
请输入一个整数(输入-1表示结束):8
1 3 5 7 8
请输入一个整数(输入-1表示结束):-1
单链表删除实验
请输入您要删除的整数(输入-1表示结束):5
1 3 7 8
请输入您要删除的整数(输入-1表示结束):1
3 7 8
请输入您要删除的整数(输入-1表示结束):7
3 8
请输入您要删除的整数(输入-1表示结束):0
找不到匹配的节点!
3 8
请输入您要删除的整数(输入-1表示结束):1
找不到匹配的节点!
3 8
请输入您要删除的整数(输入-1表示结束):-1
Process returned 0 (0x0) execution time : 23.509 s
Press any key to continue.
在FishC学C的第26天
页:
[1]