2017-04-25 105 views
0

這是我相信會是更好的方式。什麼是更好的方法?

int main() 
{ 

    node *head; 
    insertAfter(&head, 14, 12); 
} 

void insertAfter(node **head, int item, int after) 
{ 

    node *ptr, *loc; 

    loc = searchUnsorted(*head, after); //copy of *head passed 

    if(loc == (node *) NULL) 
      return; 
    ptr = (node*)malloc(sizeof(node)); 

    ptr -> info = item; 
    ptr -> next = loc -> next; 
    loc -> next = ptr; 
} 

這就是我的老師認爲的那樣。

int main() 
{ 

    node *head; 
    insertAfter(head, 14, 12); 
} 
void insertAfter(node *head, int item, int after) 
{ 

    node *ptr, *loc; 

    loc = searchUnsorted(head, after); //copy of *head passed 

    if(loc == (node *) NULL) 
      return; 
    ptr = (node*)malloc(sizeof(node)); 

    ptr -> info = item; 
    ptr -> next = loc -> next; 
    loc -> next = ptr; 
} 
+3

你們兩個都沒有設置讓我打電話給B.S的頭部。那其中之一是來自你的老師。無論如何。不清楚你是什麼樣的人)試圖做什麼和b)問題是什麼。 – John3136

+0

你所做的唯一改變是將指針傳遞給指針而不是指針?或者我錯過了什麼?你能詳細說明你爲什麼認爲你的版本更好?對我來說,沒有任何性能提升,代碼的可讀性不高。 – Outshined

+0

@Caribou你沒有錯過任何東西。我只是認爲如果我只是通過地址而不是副本,情況會好一些。這就是它的工作原理,不是嗎? –

回答

1

我認爲這個問題應該是「我應該什麼時候通過指針(即你的老師的版本),什麼時候應該傳遞一個指針指針(即你的版本)「。

在鏈接列表的上下文中,如果函數可以交換列表的頭部,則將指針傳遞給指針是有意義的。例如,考慮一個名爲insertAtFront(node**head, int item)的函數,該函數將在之前插入值,因此必須通知呼叫者關於「新」頭部。

insertAtFront(node**head, int item) { 
    node *prevHead = *head; 
    *head = createNode(item); // assign *head a new value; caller's pointer value will change 
    *head->next = prevHead; 
} 
insertAtFrontWrong(node*head, int item) { 
    node *prevHead = head; 
    head = createNode(item); // only local variable head will get new value; caller's value will not change 
    head->next = prevHead; 
} 

int main() { 
    node *main_head = createNode(10); 
    insertAtFront(& main_head,20); // OK; afterwards main_head will point to the new head 
    insertAtFrontWrong(main_head,30); // Not OK; value of main_head will remain as is 
} 

但是,如果一個函數根據定義不會交換頭部,則不需要將指針傳遞給指針;一個「普通」指針就足夠了:

void insertAfterSuperflousIndirection(node **head, int item, int after) { 
    // use (*head)->... to traverse/change successors 
    // *head will, however, never be set to a new value, so indirection is superfluous 
} 

void insertAfter(node *head, int item, int after) { 
    // use head->... to traverse/change successors 
} 

所以你的情況,如果「insertAfter」永遠不會交換頭,我寧願老師的版本。

0

你是老師試圖通過價值傳遞,你試圖通過引用傳遞。在我看來,你的方法比老師好。但它確實與你想要做的有所不同。 如果您希望在被調用函數期間更新頭指針,那麼按引用傳遞是很好的。由此,被調用者對頭指針存儲器位置所做的任何改變也在主體中更新。

假設頭 - > 0xabc123(頭的內存地址)和內容0xadf432

老師的理論insertAfter的

頭()存儲即0xadf432(主)頭部的內容。你可以玩節點,但你不能修改head(main)的內容,即不能將0xabc123的值改爲別的。

但在你的方法,你可以做到這一點。因此能夠改變頭部(主要)內容(在你的功能操作後的問題)你的頭可能指向新節點.........

相關問題