在链表尾部插入一个元素 请用C语言代码
时间: 2024-02-22 18:59:42 浏览: 88
链表尾部插入一个元素的代码如下:
```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;
}
```
以上代码会在链表尾部依次插入6、10和15三个元素,并输出整个链表的数据。
阅读全文