|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include<stdlib.h>
//void insertNode(Nod** head,int value);//因为我们插入的是第一个结点,要修改head指针的值,
//所以要传进指向Node结构体的指针
typedef struct Node
{
int value;
struct Node* next;
}Nod;
void insertNode(Nod** head, int value)
{
Nod* previous;//用previous记住上一个结点的指针
Nod* current;
Nod* new;
current = *head;
previous = NULL;
while (current != NULL && current->value < value)
{
previous = current;
current = current->next;
}
new = (Nod*)malloc(sizeof(Nod));
if (new == NULL)
{
printf("内存分配失败! \n");
exit(1);
}
new->value = value;
new->next = current;
if (previous == NULL)//当上面的while循环不被执行时previous=NULL
{
*head = new;
}
else
{
previous->next = new;
}
}
void printNode(Nod* head)
{
Nod* current;
current = head;
while (current != NULL)
{
printf("%d", current->value);
current = current->next;
}
putchar('\n');
}
void deleteNode(Nod** head, int value)
{
Nod* previous;
Nod* current;
current = *head;
previous = NULL;
while (current != NULL && current->value != value)
{
previous = current;
current = current->next;
}
if (current == NULL)
{
printf("找不到匹配的节点! \n");
return; //使整个函数结束
}
else
{
if (previous == NULL)
{
*head = current->next;
}
else
{
previous->next = current->next;
}
free(current);//释放current
}
}
int main()
{
Nod* 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;
}
函数的形参传入的是地址 跟你返不返回值没关系
你想返回值你就return ,不想返回值你就void。
简单的应用场景 比如:
形参传入地址用于返回值,函数返回int值用于判断形参是否获取值成功,成功返回 非0,失败返回0
- #include<stdio.h>
- int test(int *a)
- {
- if( *a%2!=0 )
- {
- *a = 8;
- return 1;
- }
- else
- {
- return 0;
- }
- }
- int main(void)
- {
- int a;
- a = 1;
- if( test(&a) )
- {
- printf("获取值成功:%d\n", a);
- }
- else
- {
- printf("获取值失败!\n");
- }
- return 0;
- }
复制代码
|
|