C中的指针。按功能更改列表指针的开头

时间:2017-01-29 08:28:42

标签: c list pointers

如何更改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;
}

1 个答案:

答案 0 :(得分:2)

list_pointer位于insertEntry的本地。对其值(即地址)的修改不会反映在list_pointer中定义的main中。

一如既往,您需要将指针传递给您想要修改的变量。如果变量是指针,则它需要是指向指针的指针:

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的检查,但这是它的要点。