2017-04-25 190 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的值改为别的。

但在你的方法,你可以做到这一点。因此能够改变头部(主要)内容(在你的功能操作后的问题)你的头可能指向新节点.........

相关问题