如何从其他void函数获取LinkedList地址

how to get the LinkedList address from other void functions

  1. 我想反转链表以将头指针参数提供给 reverse2 函数。

  2. 我希望 reverse2 函数反转链表并将地址替换为头指针


    //linked list//
    
    typedef struct node* lsnode;
    typedef struct node 
    {
        int data;
        lsnode link;
    }node;
    
    
    //create the 3 nodes
    
    lsnode create3() 
    {
        lsnode first, second, last;
     
        first = (lsnode)malloc(sizeof(node));
        second = (lsnode)malloc(sizeof(node));
        last = (lsnode)malloc(sizeof(node));
        first->data = 30;
        first->link = second;
        second->data = 20;
        second->link = last;
        last->data = 10;
        last->link = NULL;
    
        return first;
    }
    
    //reverse the linkedlist
    void reverse2(lsnode head)
    {
        lsnode q,p,r;
        p = head;
        q = NULL;
        r = NULL;
        while (p != NULL)
        {
            r = q;
            q = p;
            p = p->link;
            q->link = r;
        }
        head = p;
    }
    
    
    int main(void)
    {
        lsnode head = create3();
        reverse2(head);
        while (head)
        {
            printf("%d\n", head->data);
            head = head->link;
        }
        return 0;
    }

程序只打印了 30,但是我想打印 10 20 30 我的代码有什么问题..

根据评论中的一些建议,下面修改reverse2函数以传递被更改对象的地址,而不是对象本身,允许在调用中引用修改后的对象在其 return 上发挥作用。关于@Some programmer dude关于可视化价值的建议,我发现this to be helpful.
此外,为了使代码更易于理解,此代码将单字母变量名扩展为符号,任何阅读代码的人都可以更轻松地理解。

typedef struct node* lsnode;
typedef struct node 
{
    int data;
    lsnode next;//changed from link
}node;


//create the 3 nodes

lsnode create3() 
{
    lsnode first, second, last;
 
    first = (lsnode)malloc(sizeof(node));
    second = (lsnode)malloc(sizeof(node));
    last = (lsnode)malloc(sizeof(node));
    first->data = 30;
    first->next = second;
    second->data = 20;
    second->next = last;
    last->data = 10;
    last->next = NULL;

    return first;
}

//reverse the linkedlist
void reverse2(lsnode *head)//changed prototype, 
{
    //lsnode q,p,r;
    lsnode prev,current,next;//note these changes throughout
    current = *head;//note use of asterisk to reference 
                    //object being changed 
    prev = NULL;
    next = NULL;
    while (current != NULL)
    {
        next = current->next;
        current->next = prev;
        prev = current;
        current = next;
    }
    *head = prev;
}


int main(void)
{
    lsnode head = create3();
    reverse2(&head);//passes address of object to be modified
    while (head)
    {
        printf("%d\n", head->data);
        head = head->next;
    }
    return 0;
}

输出:

 10
 20
 30