单链表的基本操作代码
时间: 2023-09-21 07:04:29 浏览: 62
以下是单链表的基本操作代码示例:
```cpp
#include <iostream>
using namespace std;
// 单链表节点
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
// 在链表末尾添加节点
void addNode(ListNode*& head, int val) {
ListNode* newNode = new ListNode(val);
if (head == NULL) {
head = newNode;
} else {
ListNode* curr = head;
while (curr->next != NULL) {
curr = curr->next;
}
curr->next = newNode;
}
}
// 删除链表中指定值的节点
void deleteNode(ListNode*& head, int val) {
ListNode dummy(0);
dummy.next = head;
ListNode* prev = &dummy;
ListNode* curr = head;
while (curr != NULL) {
if (curr->val == val) {
prev->next = curr->next;
delete curr;
curr = prev->next;
} else {
prev = curr;
curr = curr->next;
}
}
head = dummy.next; // 更新头节点指针
}
// 反转链表
void reverseList(ListNode*& head) {
ListNode* prev = NULL;
ListNode* curr = head;
while (curr != NULL) {
ListNode* nextNode = curr->next;
curr->next = prev;
prev = curr;
curr = nextNode;
}
head = prev; // 更新头节点指针
}
// 打印链表
void printList(ListNode* head) {
ListNode* curr = head;
while (curr != NULL) {
cout << curr->val << " ";
curr = curr->next;
}
cout << endl;
}
int main() {
ListNode* head = NULL;
// 在链表末尾添加节点
addNode(head, 1);
addNode(head, 2);
addNode(head, 3);
addNode(head, 4);
addNode(head, 5);
// 打印链表
cout << "原始链表:";
printList(head);
// 删除链表中指定值的节点
deleteNode(head, 3);
cout << "删除节点后的链表:";
printList(head);
// 反转链表
reverseList(head);
cout << "反转后的链表:";
printList(head);
return 0;
}
```
这段代码演示了单链表的基本操作,包括在链表末尾添加节点、删除链表中指定值的节点、反转链表和打印链表。你可以根据需要进行修改和扩展。
阅读全文