69,371
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int value;
struct Node *next;
};
void insertNode(struct Node **head, int value)
{
struct Node *previous;
struct Node *current;
//struct Node *new;
struct Node *new_node;
current = *head;
previous = NULL;
while (current != NULL && current->value < value)
{
previous = current;
current = current->next;
}
new_node = (struct Node *)malloc(sizeof(struct Node));
if (new_node == NULL)
{
printf("内存分配失败!\n");
exit(1);
}
new_node->value = value;
new_node->next = current;
if (previous == NULL)
{
*head = new_node;
}
else
{
previous->next = new_node;
}
}
void printNode(struct Node *head)
{
struct Node *current;
current = head;
while (current != NULL)
{
printf("%d ", current->value);
current = current->next;
}
putchar('\n');
}
void deleteNode(struct Node **head, int value)
{
struct Node *previous;
struct Node *current;
current = *head;
previous = NULL;
while (current != NULL && current->value != value)
{
previous = current;
current = current->next;
}
if (current == NULL)
{
printf("找不到匹配的节点!\n");
return ; //为什么这里写成return 0会出错,写成return不会出错?这里的return有什么用?
}
else
{
if (previous == NULL)
{
*head = current->next;
}
else
{
previous->next = current->next;
}
free(current);
}
}
int main()
{
struct Node *head = NULL;
int input;
printf("开始测试插入整数...\n");
while (1)
{
printf("请输入一个整数(输入-1表示结束):");
scanf("%d", &input);
if (input == -1)
{
break;
}
insertNode(&head, input);
printNode(head);
}
printf("开始测试删除整数...\n");
while (1)
{
printf("请输入一个整数(输入-1表示结束):");
scanf("%d", &input);
if (input == -1)
{
break;
}
deleteNode(&head, input);
printNode(head);
}
return 0;
}
因为这个函数没有返回值