2015-02-05 71 views
0

目前,我正在尝试编写链表,但遇到问题。 当我执行下面的代码,它只是打印分配新节点后,根节点的值(空值)没有改变

当前状态:

于是我就用GDB,发现当我分配“iHead = newNode”,并返回到主,头的值没有改变! 问题是相对于通过价值/参考或任何其他?

#include <stdio.h> 
#include <stdlib.h> 

typedef struct node *nodePtr; 
struct node{ 
    int value; 
    nodePtr next; 
}; 

void print(nodePtr); 
void insert(nodePtr, int); 


int main(void){ 
    nodePtr head = NULL; 

    insert(head, 1); 
    insert(head, 2); 
    insert(head, 3); 
    insert(head, 4); 
    insert(head, 5); 

    print(head); 

    return 0; 
} 

void print(nodePtr iHead){ 
    nodePtr ptr = iHead; 

    printf("Current state:"); 
    while(ptr){ 
     printf("%d ", ptr->value); 
     ptr = ptr->next; 
    } 
    printf("\n"); 
} 

void insert(nodePtr iHead, int iValue){ 
    nodePtr newNode; 

    newNode = (nodePtr) malloc(sizeof(struct node)); 
    newNode->value = iValue; 
    newNode->next = NULL; 

    if(iHead == NULL) 
     iHead = newNode; 
    else{ 
     //find the last node 
     nodePtr ptr = iHead; 
     while(ptr -> next) 
      ptr = ptr->next; 

     //append new node 
     ptr -> next = newNode; 
    } 
} 
+0

欢迎来到Stack Overflow。请尽快阅读[关于]页面。您需要将'nodePtr *'传递给插入函数,以便它可以覆盖调用函数中的指针。或者,插入函数需要返回新的根节点:'node ='insert(nodePtr root,int value)''调用像'head = insert(head,3);'。这是一个非常普遍的问题;还有许多其他问题同构于这个问题,答案在于两种选择之一。 – 2015-02-05 18:02:01

+0

C是按值拨打的。在函数中更改函数参数不会在调用方中修改它。 – EOF 2015-02-05 18:03:19

回答

1

你正在做价值传递。

因此,在函数内完成的更改不会反映在main()中。有两种方法可以解决这个问题。

  1. void insert(nodePtr *iHead, int iValue)

通行证通过参考本功能

  • nodePtr insert(nodePtr iHead,int iValue)
  • 使在功能的变化,并返回HEAD

    main()有你的清单头部完好

    nodePtr HEAD = insert(HEAD,2); 
    
    +0

    它的作品!谢谢:) – Simon 2015-02-05 18:37:06