2012-06-29 96 views
3

我有一个链表之后,我需要的头之后创建一个节点..添加一个节点到链表头

这意味着我有这样的事情:

node *head = NULL;

,并在结束我的链表应该是这样的:

head -> node -> NULL ...

但是当我使用一个正常的ADDNODE福nction,它给了我一个运行时错误(不知道哪个,我调试有问题)...

这是我写的:

void addNode(node *head) 
{ 
node *temp = head; // a temp to not move the head 
node *newNode = (node*)malloc(sizeof(node)); // The new node 

while (temp -> next != NULL) 
{ 
    temp = temp -> next // Getting to the last node 
} 

temp -> next= newNode; // Adding the new node into the linked list insted of the NULL 
newNode -> next = NULL; // Adding the NULL after the new node 
} 

此代码的伟大工程给我时,我有一个链表已经有1个或更多的节点,但如果链表只有一个头,它会对我造成问题......我该如何解决这个问题?

(如果你不明白我的问题 - 随着ADDNODE功能我写到这里,我得到一个运行时错误添加一个新的节点进入指向已经NULL头)..

谢谢,阿米特:)

回答

2

你必须检查,如果头为null。否则,当你尝试检查

head->next != NULL 

头为空,所以你指的是随机发生在内存

如果头是NULL不能头之后添加节点。您必须为磁头分配内存,然后设置'下一个'指针。顺便说一句,为什么你要设置head-> next而head是空的?

编辑

Mayby你应该尝试添加标志节点像布尔活跃,并将其设置为false,当你想通过它。

我会试着用另一种方式说出来。你不能设置head-> next,因为head是NULL。 NULL意味着,它只是一个指针,无处可去。这是一个变量,你可以放置一些地址,但没有别的。如果妳想有就有的结构,像节点,你必须把有型节点的新对象的地址:

Node element = malloc(sizeof(Node)); 
head = element; 

后,美将在Node对象的起始地址和u可以撤销到这个结构中的变量(比如Node *)。

+0

那么如何添加头后的新节点,如果头为空? – AmitM9S6

+0

非常感谢,我可以在head后添加一个新节点,当head = null时,使用这两行代码: 'head =(node *)malloc(sizeof(node)); head - > next = null',它现在可以工作:) – AmitM9S6

+0

没问题。我的荣幸:)如果它解决了您的问题,请点击帖子下的标记。人们会知道问题解决了。 – Blood

3

需要检查,如果head是入境空,否则空指针将间接引用:

node *temp = head; /* temp set to head, possibly null. */ 

while (temp->next != NULL) /* 'temp' dereferenced, undefined behaviour 
           if 'temp' is null. */ 

为了改变被调用者可以看到,你将需要在传递node**(按照建议wildplasser),因为C通过值传递参数。更改为(例如):

void addNode(node **head) 
{ 
    node *newNode = malloc(sizeof(node)); /* No need to cast. */ 
    if (newNode) 
    { 
     newNode->next = NULL; 

     if (NULL == *head) 
     { 
      *head = newNode; /* Set the head, as there isn't one yet. */ 
     } 
     else 
     { 
      node* temp = *head; 
      while (temp->next) temp = temp->next; 
      temp->next = newNode; 
     } 
    } 
} 

这被称为:

node* my_list = NULL; 
addNode(&my_list); 
+0

头为空,但我需要照顾他添加一个节点,我不知道我怎么能这样做... '(node * head = NULL)' – AmitM9S6

+0

@AmitM9S6为什么你要在一个不存在的节点之后添加一个节点?你确定链接列表是你想要的吗? – Marlon

+0

是的,我得到了一个头设置为空,我必须添加一个节点后,但我不知道该怎么做... – AmitM9S6

1

你可以使用指针的指针:

void addNode(node **pp) 
{ 
node *newNode = malloc(sizeof *newNode); // The new node 

if (newNode) { 
    newNode->next = *pp; // steal the parent. (this will also work if *pp happens to be NULL) 
    *pp = newNode;  // let *pp point to the new node 
    } 
} 

被称为像:

... 
node *head = NULL; 
addNode(&head); 
...