写个代码插入元素到链表
时间: 2023-04-04 14:02:49 浏览: 57
这是一个很好的问题,我可以回答。以下是一个示例代码,可以将一个元素插入到链表中:
```
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void insert(struct Node** head_ref, int new_data) {
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
int main() {
struct Node* head = NULL;
insert(&head, 1);
insert(&head, 2);
insert(&head, 3);
insert(&head, 4);
insert(&head, 5);
return 0;
}
```
这个代码可以将元素 1、2、3、4、5 依次插入到链表的头部。
相关问题
用C代码实现链表插入一个元素
以下是在 C 语言中实现链表插入元素的代码示例:
```
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
void insert_node(struct node **head, int data) {
struct node *new_node = (struct node*) malloc(sizeof(struct node));
new_node->data = data;
new_node->next = *head;
*head = new_node;
}
int main() {
struct node *head = NULL;
insert_node(&head, 10);
insert_node(&head, 20);
insert_node(&head, 30);
return 0;
}
```
上面的代码定义了一个名为 `node` 的结构体,表示链表的每个节点,包含两个元素:一个整数 `data` 和一个指向下一个节点的指针 `next`。
然后,定义了一个名为 `insert_node` 的函数,它接受一个链表的头指针和要插入的整数,并在链表的头部插入一个新节点。
最后,在 `main` 函数中,创建一个名为 `head` 的指针,并使用 `insert_node` 函数插入三个整数(10、20 和 30)。
用C代码实现链表尾部插入一个元素
下面是在 C 语言中实现链表尾部插入一个元素的代码示例:
```
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
void insertAtTail(struct node** head_ref, int data) {
struct node* new_node = (struct node*) malloc(sizeof(struct node));
struct node *last = *head_ref;
new_node->data = 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;
}
int main() {
struct node* head = NULL;
insertAtTail(&head, 5);
return 0;
}
```
这段代码实现了在链表的尾部插入一个新元素的功能,具体地,它创建了一个新的节点,并将其插入到链表的最后一个节点的后面。