2013-02-25 22 views
1

這裏是我的鏈接列表包含一串鑰匙版本,持有內容的字符串表示:不知道爲什麼我的代碼沒有添加和打印我的鏈接列表?

struct node{ 
    char key[10]; 
    char content; 
struct node *next; 
}; 
struct node *head=(struct node *) NULL; 
struct node *tail=(struct node *) NULL; 

struct node * initinode(char *key, char content) 
{ 
    struct node *ptr; 
    ptr = (struct node *) calloc(1, sizeof(struct node)); 
    if(ptr == NULL)      
     return (struct node *) NULL;   
    else {         
     strcpy(ptr->key, key);   
     ptr->content = content;      
     return ptr;       
    } 
} 
void printnode(struct node *ptr) 
{ 
    printf("Key ->%s\n", ptr->key); 
    printf("Contents ->%d\n", ptr->content); 
} 
void printlist(struct node *ptr) 
{ 
    while(ptr != NULL)   
    { 
     printnode(ptr);   
     ptr = ptr->next;   
    } 
} 
void add(struct node *new) 
{ 
    if(head == NULL)  
     head = new;   
    tail->next = new;  
    tail->next = NULL;  
    tail= new;    
} 

struct node * searchname(struct node *ptr, char *key) 
{ 
    while(strcmp(key, ptr->key) != 0) {  
     ptr = ptr->next;       
     if(ptr == NULL)       
      break;         
    } 
    return ptr;         
}      

//-----------------------------add to the list number of files and print list 

int file_count = 0; 
DIR * dirp; 
struct dirent * entry; 
dirp = opendir(cwd); 
while ((entry = readdir(dirp)) != NULL) 
{ 
    if (entry->d_type == DT_REG) { /* If the entry is a regular file */ 
     file_count++; 
    } 
} 
printf("%d \n",file_count); 
char file=(char)file_count; 
closedir(dirp); 

ptr=initinode(files, file); 
add(ptr); 
printlist(head); 
//-----------------------------------casting 

在addtion到這個問題,我想不同的數據類型在它的字符串表示形式添加到我的名單。我想嘗試將它轉換爲字符串,但似乎我用於此的方法不適用於其他方法。如果你建議將一個無效的dataype潛入列表中,請詳細解釋。

謝謝

+1

關鍵字請修正對這個職位的格式。這是不可能讀的。 – 2013-02-25 23:51:07

+0

好的確定對不起,這個即時通訊新的到這個網站 – 2013-02-26 00:01:51

回答

1

在代碼中,我有一個在這裏評論

void add(struct node *new) 
{ 
    if(head == NULL)  
     head = new;   
    tail->next = new;  // Making tail point to next node 
    tail->next = NULL;  // but, immediately setting tail to NULL --> problem 
    tail= new;    // tail pointing to new but connection to previous node lost 
} 

我覺得這個功能可以

void add(struct node *new) 
{ 
    if(head == NULL) {  
     head = new; 
     tail = new; // Grow at tail and keep head static 
    } 
    else {   
     tail->next = new;  // Connect current node to next 
     tail= new;    // Move tail to new node 
     tail->next = NULL;  // Since this is the last node, set next to NULL 
    } 
} 

還有要考慮的另一個點。在這個調用中,printlist(head);你正在傳遞head指針,它在函數內部得到更新。我覺得製作head的副本並將其傳遞給該函數可能是個好主意,因此head總是指向列表的第一個元素。

P.S:請避免命名一個變量爲new,因爲它是在C++

+0

我會記住新的關鍵字。抱歉,我從來沒有學過C++。問題仍然存在於我的代碼中,因爲它仍然正確地構建它只是不正確運行。 – 2013-02-26 00:19:12

+0

@Noobprogrammer我剛剛更新了另一個小點的評論。當你說代碼運行不正確時,你能詳細說明嗎? – Ganesh 2013-02-26 00:31:15

+0

代碼將會編譯,但是當涉及到運行時,它將會失敗並且不會打印任何內容,因爲它編譯它很難指出錯誤。 – 2013-02-26 00:42:18

相關問題