在开头插入节点

时间:2014-03-06 05:20:50

标签: c

我正在制作一个代码,该代码将获取3个机场代码并将其转换为节点,然后将它们添加到列表中。以下是我到目前为止的情况:

void insertFirst(AirportCode code, Node **listPtr) {
    /* IMPLEMENT */
    //needs to add code to list, then change the head pointer
    Node* head;
    head = NULL;
    char tarray[4];
    strncpy(tarray, code, 4);
    Node* temp = (Node*)malloc(sizeof(Node));
    temp->airport = tarray;
    temp->next = head;
    head = temp;
}

/* 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;

以下部分无法更改:

/* newNode - here is a utility function to create a new node;
    node's airport set to a copy of code, and next set to NULL;
     returns a pointer to the new node */
Node *newNode(AirportCode code) {
    Node *node;
    if ((node = (Node *)malloc(sizeof(Node))) != NULL) {
        strcpy(node->airport, code);
        node->next = NULL;
    }
    else {
        fprintf(stderr, "out of memory - terminating\n");
        exit(1);
    }
    return node;
}

每次我尝试使用gcc编译它时都会收到错误:

  

数组类型'AirportCode'(又名'char [4]')不是         分配   我不知道为什么会发生这种情况,非常感谢任何帮助

2 个答案:

答案 0 :(得分:0)

你不能像这样相互指定char数组(即使你可以,它也不会产生我相信你期望的结果)。我想你想要做的是字符串分配?然后,假设您使用C ++,则应将AirportCode定义为std::string而不是char[4]

答案 1 :(得分:0)

试试这个

void insertFirst(AirportCode code, Node **listPtr) {
    Node* head = *listPtr;
    Node* temp = newNode(code);
    temp->next = head;
    *listPtr = temp;
}