单链表的插入操作的实现c语言
时间: 2023-04-05 22:00:51 浏览: 110
可以使用以下代码实现单链表的插入操作:
```c
struct ListNode {
int val;
struct ListNode *next;
};
void insertNode(struct ListNode** head, int val) {
struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
newNode->val = val;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
return;
}
struct ListNode* cur = *head;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = newNode;
}
```
这个函数的作用是在单链表的末尾插入一个新节点,如果链表为空,则直接将新节点作为头节点。
相关问题
单链表插入排序 C语言
以下是单链表插入排序的C语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
void insert(Node** head_ref, int data) {
Node* new_node = (Node*) malloc(sizeof(Node));
new_node->data = data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void printList(Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
}
void insertionSort(Node** head_ref) {
Node* sorted = NULL;
Node* current = *head_ref;
while (current != NULL) {
Node* next = current->next;
if (sorted == NULL || sorted->data >= current->data) {
current->next = sorted;
sorted = current;
} else {
Node* temp = sorted;
while (temp->next != NULL && temp->next->data < current->data) {
temp = temp->next;
}
current->next = temp->next;
temp->next = current;
}
current = next;
}
*head_ref = sorted;
}
int main() {
Node* head = NULL;
insert(&head, 5);
insert(&head, 20);
insert(&head, 4);
insert(&head, 3);
insert(&head, 30);
printf("原链表:\n");
printList(head);
insertionSort(&head);
printf("\n排序后的链表:\n");
printList(head);
return 0;
}
```
这里使用了链表的头插法来构建单链表,然后使用插入排序对链表进行排序。插入排序的时间复杂度为 O(n^2),但是对于链表这种数据结构来说,插入排序是一种比较好的排序方法。
952: 单链表的插入操作的实现c语言
可以回答这个问题。单链表的插入操作可以通过以下步骤实现:
1. 创建一个新节点,将要插入的数据存储在新节点中。
2. 找到要插入的位置,即要插入节点的前一个节点。
3. 将新节点的 next 指针指向要插入节点的下一个节点。
4. 将要插入节点的前一个节点的 next 指针指向新节点。
以下是一个示例代码:
```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;
}
void printList(struct Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
}
int main() {
struct Node* head = NULL;
insert(&head, 1);
insert(&head, 2);
insert(&head, 3);
insert(&head, 4);
printf("Linked list: ");
printList(head);
return 0;
}
```
输出结果为:Linked list: 4 3 2 1