c语言表示出单链表
时间: 2023-08-24 18:10:24 浏览: 46
单链表可以用C语言实现,以下是一个简单的示例代码:
```
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
struct ListNode {
int val;
struct ListNode *next;
};
// 创建节点
struct ListNode* createNode(int val) {
struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
newNode->val = val;
newNode->next = NULL;
return newNode;
}
// 插入节点
void insertNode(struct ListNode** head, int val) {
struct ListNode* newNode = createNode(val);
if (*head == NULL) {
*head = newNode;
} else {
struct ListNode* cur = *head;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = newNode;
}
}
// 删除节点
void deleteNode(struct ListNode** head, int val) {
if (*head == NULL) {
return;
}
struct ListNode* cur = *head;
struct ListNode* prev = NULL;
while (cur != NULL && cur->val != val) {
prev = cur;
cur = cur->next;
}
if (cur == NULL) {
return;
}
if (prev == NULL) {
*head = cur->next;
} else {
prev->next = cur->next;
}
free(cur);
}
// 打印链表
void printList(struct ListNode* head) {
struct ListNode* cur = head;
while (cur != NULL) {
printf("%d ", cur->val);
cur = cur->next;
}
printf("\n");
}
int main() {
struct ListNode* head = NULL;
insertNode(&head, 1);
insertNode(&head, 2);
insertNode(&head, 3);
insertNode(&head, 4);
printList(head);
deleteNode(&head, 2);
printList(head);
return 0;
}
```
这个示例代码实现了单链表的基本操作,包括创建节点、插入节点、删除节点和打印链表。你可以根据你的需求进行修改。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)