2012-06-29 95 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); 
...