单链表的基本操作C语言版本
时间: 2024-06-13 17:09:57 浏览: 85
单链表是一种常见的数据结构,以下是单链表的基本操作C语言版本:
1. 定义单链表节点结构体
```c
typedef struct ListNode {
int val; // 节点的值
struct ListNode *next; // 指向下一个节点的指针
} ListNode;
```
2. 创建单链表
```c
ListNode* createList(int arr[], int n) {
ListNode *head = NULL, *tail = NULL;
for (int i = 0; i < n; i++) {
ListNode *node = (ListNode*)malloc(sizeof(ListNode));
node->val = arr[i];
node->next = NULL;
if (head == NULL) {
head = tail = node;
} else {
tail->next = node;
tail = node;
}
}
return head;
}
```
3. 遍历单链表
```c
void traverseList(ListNode *head) {
ListNode *p = head;
while (p != NULL) {
printf("%d ", p->val);
p = p->next;
}
}
```
4. 插入节点
```c
void insertNode(ListNode **head, int val, int pos) {
ListNode *node = (ListNode*)malloc(sizeof(ListNode));
node->val = val;
node->next = NULL;
if (*head == NULL) {
*head = node;
return;
}
if (pos == 0) {
node->next = *head;
*head = node;
return; }
ListNode *p = *head;
for (int i = 0; i < pos - 1 && p != NULL; i++) {
p = p->next;
}
if (p == NULL) {
return;
}
node->next = p->next;
p->next = node;
}
```
5. 删除节点
```c
void deleteNode(ListNode **head, int pos) {
if (*head == NULL) {
return;
}
if (pos == 0) {
ListNode *p = *head;
*head = (*head)->next;
free(p);
return;
}
ListNode *p = *head;
for (int i = 0; i < pos - 1 && p != NULL; i++) {
p = p->next;
}
if (p == NULL || p->next == NULL) {
return;
}
ListNode *q = p->next;
p->next = q->next;
free(q);
}
```
阅读全文