2014-03-06 138 views
0

我正在寫一個函數,它將採用已創建的鏈接列表並將該鏈接列表複製到另一個鏈接列表中。這是我迄今爲止複製鏈接列表到另一個鏈接列表

/* defined types: 
    AirportCode is an alias for a 4-char array 
    Node is a linked list node (struct) for AirportCodes */ 
typedef char AirportCode[4]; 
typedef struct node { 
    AirportCode airport; 
    struct node *next; 
} Node; 

Node *copy(Node *list) { 
/* REPLACE THIS NON-SOLUTION */ 
struct node *temp = (struct node *)malloc(sizeof(struct node)); 
temp->airport = list->airport; 
temp->next = copy(list->next); 
return(temp); 

return NULL; 
} 

/* test copy, and print the copy */ 
    list3 = copy(list1); 
    printf("list3 copied from list1: "); printList(list3); 

當我嘗試編譯這個使用gcc我得到的錯誤:

airports.c:50:19: error: array type 'AirportCode' (aka 'char [4]') is not 
     assignable 
    temp->airport = list->airport; 
    ~~~~~~~~~~~~~^
1 error generated. 

任何想法?

+1

'memcpy(temp-> airport,list-> airport,sizeof(AirportCode))' – michaelmeyer

回答

0

顯而易見的問題是編譯器報告的問題:您不能複製char數組的內容,只是將一個char分配給另一個。如果它能工作,它會將一個指向數組第一個位置的指針指向另一個,這不是你想要的。

必須通過位置複製陣列位置中的內容,與任一:

strcpy(temp->airport, list->airport); 

(提供可以在每個機場代碼末尾添加零,作爲AirportCode 5的陣列,其中上另一方面會浪費很多的空間),或更好的:

memcpy(temp->airport, list->airport, sizeof(AirportCode)) 

無論如何,這是不會解決實際問題:你是不是在你的函數copy()複製列表。我該函數重命名爲copyNode()

Node *copyNode(Node *list) 
{ 
    struct node *temp = (struct node *)malloc(sizeof(struct node)); 
    temp->airport = list->airport; 
    temp->next = copy(list->next); 
    return(temp); 
} 

現在,你可以創建一個真正的功能副本:

Node *copy(Node *list) 
{ 
    Node * toret = NULL; 
    Node * ptrList = list; 

    while(ptrList != NULL) { 
     if (toret == NULL) { 
      toret = copyNode(ptrList); 
     } else { 
      toret->next = copyNode(ptrList); 
      toret = toret->next; 
     } 

     ptrList = ptrList->next; 
    } 

    return toret; 
} 

請注意,您的列表應該用NULL作爲在下一指針結束最後的節點。

希望這會有所幫助。