我创建了一个链表并通过引用返回,由于某种原因,将其发送到另一个函数后,除非我再次通过引用将其发送,否则它不会返回更改,原因何在?
如果我只是将“ lst”作为没有“&”的lst发送给函数,那么当它从函数返回时,我只会得到一个奇数列表。当我在函数内部使用调试器时,我看到了带有偶数的列表值(也应该在主值中),因为我认为应该这样,因为lst是像数组一样的基地址,还是我错了?
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
}node;
node* get_lst(node **linked_lst);
node *createList2(node** L);
void main() {
node *odd_node = NULL, *lst = NULL;
get_lst(&lst);//get values for the original list
odd_node = createList2(&lst);//get an odd list
getch();
}
node *createList2(node **L)
{
node * tList = *L, odd_lst;
node *temp_odd = &odd_lst;
temp_odd->next = NULL;
//first element in the list is odd
while (tList != NULL && tList->data % 2)
{
temp_odd->next = tList;
tList = tList->next;
*L = tList;
temp_odd = temp_odd->next;
temp_odd->next = NULL;
}
//first element in the list is even
while (tList != NULL)
{
if (tList->next != NULL && tList->next->data % 2)
{
temp_odd->next = tList->next;
tList->next = tList->next->next;
temp_odd = temp_odd->next;
temp_odd->next = NULL;
}
else
tList = tList->next;
}
return odd_lst.next;
}
node* get_lst(node **linked_lst) {
int value;
node *curr = NULL;
node *new_node;
do
{
printf("enter value:");
scanf_s("%d", &value);
if (value <0) {
return NULL;
}
new_node = (node*)malloc(sizeof(node));
new_node->data = value;
new_node->next = NULL;
if (*linked_lst == NULL)
{
*linked_lst = new_node;
curr = *linked_lst;
}
else
{
curr->next = new_node;
curr = curr->next;
}
} while (value >= 0);
return *linked_lst;
}