如何更改 list_pointer
的开头?我试图通过比较两个指针来实现这一点。但它只能在一个函数内工作。
或者我需要为 exmple struct entry head
创建新结构?
// Function to insert a new entry into a linked list.
#include <stdio.h>
struct entry
{
int value;
struct entry *next;
};
void insertEntry(struct entry *insertion, struct entry *previous, struct entry *list_pointer)
{ // 1 < 100
if (insertion->value < previous->value) {
// n0 = n1
insertion->next = previous;
// = n0 // start from n0 insted of n1
list_pointer = insertion;
// list_pointer is set to point to n0 only here inside this fuction
}
else {
insertion->next = previous->next; // set n2_3.next to point to whatever n2.next was pointing to
previous->next = insertion; // set n2.next to point to n2_3
}
}
void printPlist(struct entry *list_pointer)
{
while (list_pointer != (struct entry *) 0) {
printf("%i\n", list_pointer->value);
list_pointer = list_pointer->next;
}
printf("\n");
}
int main(void)
{
struct entry n3 = { .value = 300,.next = (struct entry *) 0 };
struct entry n2 = { .value = 200,.next = &n3 };
struct entry n1 = { .value = 100,.next = &n2 };
struct entry *list_pointer = &n1;
//struct entry n2_3 = { .value = 250 }; // insertion
struct entry n0 = { .value = 1 }; // insertion
printPlist(list_pointer);
insertEntry(&n0, &n1, list_pointer);
printPlist(list_pointer);
return 0;
}
最佳答案
list_pointer
对于 insertEntry
是本地的。并且对其值(地址)的修改不会反射(reflect)在您在 main
中定义的 list_pointer
中。
与往常一样,您需要传递一个指向您希望修改的变量的指针。如果变量是指针,则需要是指向指针的指针:
void insertEntry(struct entry *insertion, struct entry *previous, struct entry **p_list_pointer)
{ // 1 < 100
if (insertion->value < previous->value) {
// n0 = n1
insertion->next = previous;
// = n0 // start from n0 insted of n1
*p_list_pointer = insertion;
// list_pointer is set to point to n0 only here inside this fuction
}
else {
insertion->next = previous->next; // set n2_3.next to point to whatever n2.next was pointing to
previous->next = insertion; // set n2.next to point to n2_3
}
}
我省略了对 p_list_pointer
的 NULL 检查,但这就是它的要点。
关于c - C中的指针。通过函数更改列表指针的开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41918988/