2014-01-25 124 views
3

我是C新手,也是編程新手,我剛開始查看鏈表。將新節點鏈接到鏈接列表中的問題c

static struct post { 
    char * str; 
    struct post * next; 
} 
head = {0, NULL}; 


int stringdb_add(const char * str) { 
    int pos = 0; 
    struct post * new_input = (struct post *) malloc(sizeof(struct post)); 
    new_input - > str = (char *) malloc(strlen(str) + 1); 

    if (head.next == NULL) { 
     strcpy(new_input - > str, str); 
     new_input - > next = NULL; 
     head.next = new_input; 
    } else { 
     while (head.next - > next) { 
      ++pos; 
      head.next = head.next - > next; 
     } 
     strcpy(new_input - > str, str); 
     new_input - > next = NULL; 
     head.next - > next = new_input; 
    } 

    return pos; 
} 

功能「stringdb_add」應該返回新節點已被放置的位置,但是當我測試的功能,我只得到(00111111 ....)。

這可能是因爲該列表從不正確鏈接。

+0

你得到一個+1的嘗試..但可能會得到一個-1的縮進 - 排序它 –

回答

3
while (head.next->next) { 
    ++pos; 
    head.next = head.next->next;   
} 

要永久改變head.next這肯定不是你想要的。你可能想是這樣的:

struct post *p = &head; 
while (p->next->next) 
/* ... */ 

雞蛋裏挑骨頭:strcpy(new_input->str, str)可以在一個地方,在if之前。

+0

好吧,我總是得到它現在的工作,整個p指針使一切更容易。感謝您的幫助和真正的qucik答案! :) – Adlon