在链表尾部插入一个节点并且函数只传入一个参数 请用C语言代码实现
时间: 2024-02-22 14:59:44 浏览: 14
链表尾部插入一个节点并且只传入一个参数的函数代码如下:
```c
struct Node {
int data;
struct Node* next;
};
void insertAtEnd(struct Node** head_ref, int new_data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
struct Node* last = *head_ref;
new_node->data = new_data;
new_node->next = NULL;
if (*head_ref == NULL) {
*head_ref = new_node;
return;
}
while (last->next != NULL)
last = last->next;
last->next = new_node;
return;
}
```
调用该函数的示例代码如下:
```c
int main() {
struct Node* head = NULL;
insertAtEnd(&head, 6);
insertAtEnd(&head, 10);
insertAtEnd(&head, 15);
// 遍历链表并输出
struct Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
return 0;
}
```
该函数只传入一个参数head_ref,需要将其类型定义为指向指针的指针。在函数内部,需要动态分配一个新节点,并将新节点插入链表尾部。当链表为空时,需要特殊处理。最后,需要将插入后的链表返回给调用者。