|
在find_lklist()子程序中,如何返回要查找的结点。且在主程序能正确显示其值。能不能出了子程序return p;主程序p= find_lklist()外其他方法,如我这种方法。在参数中直接返回。
[code:1]
/*带头结点的单链表*/
#include <stdio.h>
typedef struct node
{
int data;
struct node *next;
} lklist;
int main (void)
{
lklist *head, *p;
int input;
int output;
int count;
printf("请输入一些数字(0为结束):");
initiate_lklist(&head);
create_lklist(&head);
print_lklist(&head);
printf("请输入要查找的序号:");
scanf("%d", &input);
find_lklist(&head, input, &p);
printf("第%d号的值为%d\n", input, *p);
printf("请输入要查找的值:");
scanf("%d", &input);
locate_lklist(&head, input, &output);
printf("该值%d的位置是%d\n", input, output);
}
int initiate_lklist (lklist **head)
{
(*head) = (lklist *) malloc (sizeof(lklist));
(*head) -> next = NULL;
}
int create_lklist (lklist **head)
{
lklist *new, *end;
int x;
end = *head;
scanf("%d", &x);
while (x != 0)
{
new = (lklist *) malloc (sizeof(lklist));
new -> data = x;
end -> next = new;
end = new;
scanf("%d", &x);
}
end -> next = NULL;
}
int print_lklist (lklist **head)
{
lklist *p;
int j = 1;
p = *head;
printf("最新的排列:");
if ((*head) != NULL)
{
p = p -> next;
while (p != NULL)
{
printf("(%d):", j);
j++;
printf("%d ", p -> data);
p = p -> next;
}
}
printf("\n");
}
int find_lklist (lklist **head, int i, lklist *p)
{
int j = 0;
p = *head;
while ((p -> next != NULL) && (j < i))
{
p = p -> next;
j++;
}
if (i == j)
return 1;
else
{
printf("该位置不存在!\n");
return 0;
}
}
int locate_lklist (lklist **head, int x, int *output)
{
lklist *p;
int j = 0;
p = *head;
while ((p -> next != NULL) && (p -> data != x))
{
p = p -> next;
j++;
}
if (p -> data == x)
{
*output = j;
return 1;
}
else
{
printf("\n该值不存在!\n");
return 0;
}
}
[/code:1] |
|