c++单链表的头插法和尾插法
作者:野牛程序员:2023-11-26 11:52:35 C++阅读 2777
头插法和尾插法是单链表常见的两种插入方式。下面是C++中的完整代码示例:
#include <iostream>
// 定义链表节点
struct Node {
int data;
Node* next;
Node(int value) : data(value), next(nullptr) {}
};
// 头插法插入节点
Node* insertAtBeginning(Node* head, int value) {
Node* newNode = new Node(value);
newNode->next = head;
return newNode;
}
// 尾插法插入节点
Node* insertAtEnd(Node* head, int value) {
Node* newNode = new Node(value);
if (head == nullptr) {
return newNode;
}
Node* current = head;
while (current->next != nullptr) {
current = current->next;
}
current->next = newNode;
return head;
}
// 打印链表
void printList(Node* head) {
Node* current = head;
while (current != nullptr) {
std::cout << current->data << " ";
current = current->next;
}
std::cout << std::endl;
}
int main() {
// 初始化链表头节点为空
Node* head = nullptr;
// 头插法插入节点
head = insertAtBeginning(head, 3);
head = insertAtBeginning(head, 2);
head = insertAtBeginning(head, 1);
// 打印链表
std::cout << "链表(头插法): ";
printList(head);
// 重新初始化链表头节点为空
head = nullptr;
// 尾插法插入节点
head = insertAtEnd(head, 1);
head = insertAtEnd(head, 2);
head = insertAtEnd(head, 3);
// 打印链表
std::cout << "链表(尾插法): ";
printList(head);
return 0;
}请注意,这只是一个简单的例子,用于演示头插法和尾插法。在实际应用中,可能需要添加更多的功能和错误处理。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:c++单链表从文件里提取数据
- 下一篇:c语言从文件读取数据到链表
