链表代码
时间: 2023-06-28 20:15:55 浏览: 60
链表是一种常见的数据结构,它由节点组成,每个节点包含了一个数据元素和一个指向下一个节点的指针。链表可以用于实现队列、栈等数据结构。
以下是一个简单的链表的定义和基本操作的示例代码。
```c++
// 链表节点的定义
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
// 在链表末尾添加一个节点
void appendListNode(ListNode*& head, int val) {
ListNode* newNode = new ListNode(val);
if (head == nullptr) {
head = newNode;
} else {
ListNode* cur = head;
while (cur->next != nullptr) {
cur = cur->next;
}
cur->next = newNode;
}
}
// 删除链表中的一个节点
void deleteListNode(ListNode*& head, int val) {
if (head == nullptr) {
return;
}
if (head->val == val) {
ListNode* toDelete = head;
head = head->next;
delete toDelete;
} else {
ListNode* cur = head;
while (cur->next != nullptr && cur->next->val != val) {
cur = cur->next;
}
if (cur->next != nullptr) {
ListNode* toDelete = cur->next;
cur->next = cur->next->next;
delete toDelete;
}
}
}
// 打印链表的值
void printList(ListNode* head) {
ListNode* cur = head;
while (cur != nullptr) {
std::cout << cur->val << " ";
cur = cur->next;
}
std::cout << std::endl;
}
// 清空链表
void clearList(ListNode*& head) {
while (head != nullptr) {
ListNode* toDelete = head;
head = head->next;
delete toDelete;
}
}
int main() {
ListNode* head = nullptr;
appendListNode(head, 1);
appendListNode(head, 2);
appendListNode(head, 3);
printList(head); // 输出 1 2 3
deleteListNode(head, 2);
printList(head); // 输出 1 3
clearList(head);
return 0;
}
```
这段代码定义了一个链表节点结构体 `ListNode`,包含一个整型数据成员 `val` 和一个指向下一个节点的指针成员 `next`。然后定义了一些基本操作函数,包括在链表末尾添加一个节点、删除一个节点、打印链表的值和清空链表。最后在 `main` 函数中演示了这些操作的使用。
相关推荐
![h](https://img-home.csdnimg.cn/images/20210720083646.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)