C语言链表操作
时间: 2023-06-21 09:11:16 浏览: 108
链表是一种常见的数据结构,它可以用来实现各种算法和数据结构。C语言中,链表可以通过结构体和指针来实现。下面是链表的基本操作:
1. 定义链表节点结构体
```
struct ListNode {
int val;
struct ListNode *next;
};
```
2. 创建链表节点
```
struct ListNode* createNode(int val) {
struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = val;
node->next = NULL;
return node;
}
```
3. 插入节点到链表头部
```
void insertAtHead(struct ListNode** head, int val) {
struct ListNode* node = createNode(val);
node->next = *head;
*head = node;
}
```
4. 插入节点到链表尾部
```
void insertAtTail(struct ListNode** head, int val) {
struct ListNode* node = createNode(val);
if (*head == NULL) {
*head = node;
return;
}
struct ListNode* tail = *head;
while (tail->next != NULL) {
tail = tail->next;
}
tail->next = node;
}
```
5. 删除节点
```
void deleteNode(struct ListNode** head, int val) {
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);
}
```
6. 查找节点
```
struct ListNode* searchNode(struct ListNode* head, int val) {
struct ListNode* cur = head;
while (cur != NULL && cur->val != val) {
cur = cur->next;
}
return cur;
}
```
7. 遍历链表
```
void printList(struct ListNode* head) {
struct ListNode* cur = head;
while (cur != NULL) {
printf("%d ", cur->val);
cur = cur->next;
}
printf("\n");
}
```
这些是链表的基本操作,可以根据需要进行扩展。
阅读全文
相关推荐









