C++ 链表构建与显示:示例代码和详细解释
#include
// 定义链表的节点 struct Node { int data; // 数据 Node* next; // 指向下一个节点的指针 };
// 定义链表的头节点 Node* head = NULL;
// 在链表末尾插入新节点 void insert(int value) { Node* newNode = new Node; newNode->data = value; newNode->next = NULL; if (head == NULL) { head = newNode; } else { Node* curr = head; while (curr->next != NULL) { curr = curr->next; } curr->next = newNode; } }
// 显示链表中的所有节点 void display() { Node* curr = head; while (curr != NULL) { cout << curr->data << ' '; // 使用单引号 curr = curr->next; } }
int main() { // 向链表中插入数据 insert(1); insert(2); insert(3); insert(4); insert(5);
// 显示链表中的所有节点
display();
return 0;
}
// 输出结果为:1 2 3 4 5
原文地址: https://www.cveoy.top/t/topic/mI6D 著作权归作者所有。请勿转载和采集!