请写出一段链表插入结点的c语言代码
时间: 2023-10-16 15:09:34 浏览: 40
struct Node {
int data;
struct Node* next;
};
void insertNode(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;
}
相关问题
请为我写一段计算双向链表长度的c语言代码
以下是一个简单的计算双向链表长度的C语言代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* prev;
struct Node* next;
};
// 计算双向链表长度
int countNodes(struct Node* head) {
int count = 0;
struct Node* current = head;
while (current != NULL) {
count++;
current = current->next;
}
return count;
}
int main() {
// 创建双向链表
struct Node* head = (struct Node*)malloc(sizeof(struct Node));
struct Node* second = (struct Node*)malloc(sizeof(struct Node));
struct Node* third = (struct Node*)malloc(sizeof(struct Node));
head->data = 1;
head->prev = NULL;
head->next = second;
second->data = 2;
second->prev = head;
second->next = third;
third->data = 3;
third->prev = second;
third->next = NULL;
// 计算双向链表长度并打印结果
int length = countNodes(head);
printf("双向链表的长度为: %d\n", length);
// 释放内存
free(head);
free(second);
free(third);
return 0;
}
```
上述代码中,我们创建了一个双向链表,并定义了一个计算链表长度的函数`countNodes()`。函数中使用一个计数器`count`遍历整个链表,并在遍历每个节点时将计数器加1。最终返回计数器的值即为链表的长度。在主函数中,我们调用了`countNodes()`函数来计算链表长度,并打印结果。最后,我们释放了双向链表中的所有节点的内存。
请用c语言写出一段链表及其基本操作
好的,下面是用 C 语言实现链表及其基本操作的代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct ListNode {
int val;
struct ListNode* next;
} ListNode;
// 初始化链表
ListNode* initList() {
ListNode* head = (ListNode*)malloc(sizeof(ListNode)); // 创建头节点
head->next = NULL;
return head;
}
// 在链表末尾插入一个节点
void insert(ListNode* head, int val) {
ListNode* node = (ListNode*)malloc(sizeof(ListNode)); // 创建新节点
node->val = val;
node->next = NULL;
ListNode* p = head;
while (p->next != NULL) { // 找到链表末尾
p = p->next;
}
p->next = node; // 将新节点插入到链表末尾
}
// 删除链表中第一个值为 val 的节点
void delete(ListNode* head, int val) {
ListNode* p = head;
while (p->next != NULL && p->next->val != val) { // 找到第一个值为 val 的节点
p = p->next;
}
if (p->next != NULL) { // 找到了,删除该节点
ListNode* node = p->next;
p->next = node->next;
free(node);
}
}
// 遍历链表并打印每个节点的值
void traverse(ListNode* head) {
ListNode* p = head->next; // 从第一个节点开始遍历
while (p != NULL) {
printf("%d ", p->val);
p = p->next;
}
printf("\n");
}
int main() {
ListNode* head = initList(); // 初始化链表
insert(head, 1); // 在链表末尾插入节点
insert(head, 2);
insert(head, 3);
insert(head, 4);
traverse(head); // 遍历链表并打印每个节点的值
delete(head, 3); // 删除值为 3 的节点
traverse(head); // 再次遍历链表并打印每个节点的值
return 0;
}
```
以上就是使用 C 语言实现链表及其基本操作的代码。