C语言中单链表的插入代码
时间: 2023-03-28 16:01:35 浏览: 82
以下是单链表的插入代码:
```c
#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);
printf("Inserted elements: ");
struct Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
return ;
}
```
以上是单链表的插入代码,希望对你有所帮助。
相关问题
用C语言实现单链表插入时进行排序
可以使用头插法或者尾插法来实现单链表的插入排序。具体实现方法可以参考以下代码:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
void insert(Node** head, int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
return;
}
Node* curr = *head;
Node* prev = NULL;
while (curr != NULL && curr->data < data) {
prev = curr;
curr = curr->next;
}
if (prev == NULL) {
newNode->next = *head;
*head = newNode;
} else {
prev->next = newNode;
newNode->next = curr;
}
}
void printList(Node* head) {
Node* curr = head;
while (curr != NULL) {
printf("%d ", curr->data);
curr = curr->next;
}
printf("\n");
}
int main() {
Node* head = NULL;
insert(&head, 3);
insert(&head, 1);
insert(&head, 5);
insert(&head, 2);
insert(&head, 4);
printList(head);
return 0;
}
```
c语言实现单链表的插入
以下是c语言实现单链表的插入的代码:
```c
#include <stdio.h>
#include <stdlib.h>
//定义链表节点
typedef struct node {
int data;
struct node *next;
} Node;
//插入节点
void insert(Node **head, int data) {
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
} else {
Node *current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
//输出链表
void printList(Node *head) {
Node *current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
Node *head = NULL;
insert(&head, 1);
insert(&head, 2);
insert(&head, 3);
insert(&head, 4);
insert(&head, 5);
printList(head);
return 0;
}
```
在上面的代码中,我们首先定义了一个节点结构体,包含了数据和指向下一个节点的指针。然后定义了插入函数,用于在链表末尾插入节点。如果链表为空,则将新节点作为头节点,否则遍历链表找到最后一个节点,将新节点插入到其后面。最后,定义了一个输出链表的函数,用于打印链表中的所有节点。在主函数中,我们创建了一个空的链表,并插入了一些节点,最后输出整个链表。