C++ 单链表尾插法实现:创建带头节点的链表
#include
// 定义链表节点结构体 struct Node { int data; Node* next; };
// 创建链表函数 Node* createList() { Node* head = new Node(); // 创建头节点 head->next = nullptr; // 头节点的next指针置空
Node* tail = head; // 初始化尾指针为头节点
int num;
cout << "请输入节点数目: ";
cin >> num;
// 依次输入节点的值并尾插入链表
for (int i = 0; i < num; i++) {
int value;
cout << "请输入第" << i + 1 << "个节点的值: ";
cin >> value;
Node* newNode = new Node(); // 创建新节点
newNode->data = value; // 设置节点的数据
newNode->next = nullptr; // 新节点的next指针置空
tail->next = newNode; // 尾节点的next指针指向新节点
tail = newNode; // 更新尾指针
}
return head; // 返回头节点
}
// 打印链表函数 void printList(Node* head) { Node* p = head->next; // 从第一个节点开始遍历
cout << "链表的元素为: ";
while (p != nullptr) {
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
int main() { Node* head = createList(); printList(head);
return 0;
}
原文地址: https://www.cveoy.top/t/topic/IJq 著作权归作者所有。请勿转载和采集!