如何使用建立一个链表?
时间: 2023-05-21 14:01:57 浏览: 75
要建立一个链表,需要定义一个节点结构体,包含数据和指向下一个节点的指针。然后,可以通过不断创建新节点并将它们连接起来来构建链表。以下是一个示例代码:
```
struct Node {
int data;
struct Node* next;
};
struct Node* head = NULL;
void addNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
} else {
struct Node* current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
// 示例用法
addNode(1);
addNode(2);
addNode(3);
```
这将创建一个包含三个节点的链表,每个节点包含一个整数数据和指向下一个节点的指针。
相关问题
用c语言建立一个二叉链表
可以按照以下步骤建立一个二叉链表:
1. 定义二叉树的结点结构体:
```c
struct TreeNode {
int data; // 结点数据
struct TreeNode *left; // 左子结点指针
struct TreeNode *right; // 右子结点指针
};
```
2. 定义二叉树的创建函数:
```c
struct TreeNode* createTree() {
int data;
scanf("%d", &data);
if (data == -1) { // -1 表示该结点为空
return NULL;
}
struct TreeNode *root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->data = data;
root->left = createTree();
root->right = createTree();
return root;
}
```
3. 调用创建函数创建二叉树:
```c
struct TreeNode *root = createTree();
```
这样就可以用 C 语言建立一个二叉链表了。
用c语言建立一个动态链表
好的,我可以为您提供一个简单的C语言动态链表的实现代码,如下所示:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
struct Node {
int data;
struct Node* next;
};
// 插入节点函数
void insert_node(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 delete_node(struct Node** head_ref, int key) {
struct Node* temp = *head_ref, *prev;
if (temp != NULL && temp->data == key) {
*head_ref = temp->next;
free(temp);
return;
}
while (temp != NULL && temp->data != key) {
prev = temp;
temp = temp->next;
}
if (temp == NULL) return;
prev->next = temp->next;
free(temp);
}
// 打印链表函数
void print_list(struct Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
}
// 示例
int main() {
struct Node* head = NULL;
insert_node(&head, 1);
insert_node(&head, 2);
insert_node(&head, 3);
insert_node(&head, 4);
printf("链表为:");
print_list(head);
delete_node(&head, 3);
printf("\n删除节点后链表为:");
print_list(head);
return 0;
}
```
这段代码实现了一个简单的动态链表,具有插入节点、删除节点和打印链表功能。您可以根据需要进行修改和扩展。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![md](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)