簡體   English   中英

按值將鏈表傳遞給 function

[英]passing linked list to function by value

編輯:我的結構是形式:

         struct node{
             int key;
             struct node* next;
         }
         typedef struct node* LIST;

我正在編寫一個名為print_list_iteratively的 function ,它采用單鏈表並以相反的順序迭代地打印其元素。 讓我把我的 3 個函數放在下面,然后解釋一下我的問題是什么?

         LIST reverse_list(LIST L) {
              LIST current = L, prev = NULL, subsequent = NULL;
              while (current != NULL) {
                // first we need to get the next element to not lose the link.
                subsequent = current->next;

                // now reverse the pointer
                current->next = prev;

                // we need to update our prev to create link between the currrent and next element.
                // in short, we need to get the address of current node
                prev = current;

                // finally update the current
                current = subsequent;
             }
             return (L = prev);
        }

上述代碼反轉列表 L,並返回列表 L 的新頭部。

        void print_list(LIST L) {
             while (L) {
                printf("%d  ", L->key);
                L = L->next;
             }
        }

print_list按連接順序打印列表中的元素。

開頭提到的print_list_iteratively function我都需要寫。

        void print_list_iteratively(LIST l) {
            // first reverse the list, then call print_list. that's all.
            printf("address of function parameter is %p\n", l);
            l = reverse_list(l);
            print_list(l);
        }

我對這些功能沒有問題; 它們按預期工作,但是當我試圖了解 function 如何將列表作為參數並返回它時,按值傳遞和按引用傳遞的概念讓我感到困惑。 讓我簡單地寫一個 main 來測試這些,我們會看看事情是如何混合起來的。

         int main(void) {
             l = insert(l, 5);
             l = insert(l, 10);
             l = insert(l, 15);
             l = insert(l, 45);
             print_list(l);
             print_list_iteratively(l);
             print_list(l);
             return 0;
         }

當第一個print_list function 被調用時,它會打印5->10->15->45. 下一個print_list_iteratively在列表l上被調用,它又在 function 的主體中調用reverse_listprint_list print_list中的print_list_iteratively給出反向列表45->15->10->5. 最終,main 中的print_list打印出5.
我想知道為什么第二個print_list剛剛打印了5 我已經將列表發送到print_list_iteratively pass by value,而不是通過引用,盡管如此,它改變了我的原始列表 insinde main function。 有人能解釋一下這個例子中的列表是如何傳遞給函數的,以及它們是如何從函數中返回的嗎? 我很感激你的回答。

問題是您按值傳遞頭指針。 這使您的程序可以修改您的鏈表,但頭指針保持不變。

您應該通過引用或指向您的指針的指針將頭指針傳遞給 function。 node*& or node** )請記住,如果您通過指針傳遞它,則需要在需要時取消引用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM