2016-02-19 74 views
0

我想做一個插入函數,但我不知道我是否被允許在參數中使用char字符串和節點。插入函數使用strcmp()

這是行不通的?爲什麼不?

void insert(char* str, node* head) { 
     if (head == NULL) { 
     node* new_node = malloc(sizeof(struct node)); 
     assert(new_node != NULL); 
     new_node->value = strdup(str); 
    } 
    while (head != NULL) { 
     if (strcmp(str, head->value)) { 
     node *new_node = malloc(sizeof(struc node)); 
     assert(new_node != NULL); 
     new_node->link = head; 
     new_node->value - strdup(str); 
     } 
    } 
    node *prev = head; 
    head = head->link; 
+2

「這是否工作?測試它,你會知道。通過查看代碼很難看出它是否工作 - 除非你是真正的專家。 – Ian

+1

這也不是所有的代碼。只有你有足夠的代碼才能知道它是否有效。 – e0k

+0

注意'head = head-> link;'在函數範圍內修改'head'的值,但不在它之外。函數在參數副本上工作。爲了解決這個問題,即使它已經是一個指針,也要通過指針傳遞'head'。嘗試'void insert(char * str,node ** head)'和'if(* head == NULL)...' – francis

回答

1

您還沒有按返回值返回列表的新頭部。如果插入一個節點,則必須爲一個節點分配內存。不要忘了第一個節點的初始化成員prev最後節點與NULL成員link

node* insert(char* str, node* head) 
{ 
    node* new_node = malloc(sizeof(struct node)); 
    assert(new_node != NULL); 
    new_node->value = strdup(str); 
    new_node->link = NULL;   // successor of new node is NULL 

    if (head == NULL) 
    { 
     new_node->pev = NULL;  // prdecessor of first node is NULL 
     head = new_node; 
     return new_node;   // head was NULL, return new head 
    } 

    node *lastNode = head;   // go to last node of list 
    while (head->link != NULL) 
     lastNode = lastNode->link; // step one forward 

    lastNode->link = new_node;  // successor of last node is new node 
    new_node->prev = lastNode;  // predecesor of new node is last node 
    return head; 
} 

-

node *head = NULL; 
head = insert("abc", head); 
head = insert("def", head); 

另一個解決方法是使用一個在輸出放慢參數你在功能insert放慢參數head

void insert(char* str, node** head) 
         // ^^ in and output parameter 
{ 
    node* new_node = malloc(sizeof(struct node)); 
    assert(new_node != NULL); 
    new_node->value = strdup(str); 
    new_node->link = NULL;   // successor of new node is NULL 

    node* prev = NULL; 
    node* act = *head; 
    while (act != NULL)   // go to last node in list 
    { 
     prev = act; 
     act = act->link;   // step one forward 
    } 

    new_node->prev = prev;  // predecessor of new node is last node or NULL 
    if (prev == NULL) 
     *head = new_node;  // new node is the first node in list, 
          // write the new node back to head 
    else 
     prev->link = new_node; // successor of last node is new node 
} 

-

node *head = NULL; 
insert("abc", &head); 
insert("def", &head);