利用c++实现a. 构建一个含有头结点的链表,头结点之后的第一个结点位置为0号位置
时间: 2024-09-21 20:08:09 浏览: 61
在C++中,你可以通过定义一个简单的结构体或者类来表示链表的节点,并创建一个头结点作为链表的起点。下面是一个基础的单向链表实现:
```cpp
#include <iostream>
// 定义链表节点
struct ListNode {
int data;
ListNode* next; // 指向下一个节点的指针
// 构造函数
ListNode(int val = 0) : data(val), next(nullptr) {}
};
// 创建链表的头结点
ListNode* createLinkedListWithHead() {
// 创建头结点
ListNode* head = new ListNode();
return head;
}
// 在链表特定位置插入节点
void insertNode(ListNode*& head, int data, int position) {
if (position <= 0) {
std::cout << "插入位置不合理!" << std::endl;
return;
}
ListNode* newNode = new ListNode(data);
if (position == 1) {
// 如果要在头部插入
newNode->next = head;
head = newNode;
} else {
ListNode* current = head;
for (int i = 1; i < position; ++i) {
if (current->next == nullptr) {
std::cout << "插入位置超出链表长度!" << std::endl;
return;
}
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
}
}
int main() {
// 创建头结点
ListNode* head = createLinkedListWithHead();
// 插入示例节点(假设输入的1, 2, 3...)
for (int i = 1; i < 6; ++i) {
insertNode(head, i, i); // 第i个位置插入i
}
// 输出链表
printLinkedList(head); // 自己实现一个遍历打印链表的函数
return 0;
}
```
这段代码首先创建了一个链表的头结点,然后按照给定的`position`值插入新的节点。注意,这里的`position`是从1开始计数的,所以实际上插入的是第0、1、2...位置的节点。
阅读全文
相关推荐


















