C++不使用Node类指针实现链表:display方法无限循环求助
问题:C++链表直接用Node对象实现时display方法无限循环的解决办法
错误分析
- insert方法逻辑错误:
你在insert中创建的Node t是局部变量,函数执行完后t会被销毁。虽然将t赋值给成员变量head,但t.link指向的是赋值前head的地址,赋值后head内容被覆盖,导致head.link指向自身,形成自环。同时每次insert都会覆盖head,之前的节点数据完全丢失,链表实际只有一个自环节点。 - display方法遍历错误:
循环中你将t赋值为*head.link,这会让t每次都重置为head的下一个节点(也就是head自己),而非当前t的下一个节点,导致循环无法前进,陷入无限循环。
修正后的标准链表实现(使用动态节点指针)
标准链表实现依赖动态分配的节点指针,能灵活增删节点,也是新手优先掌握的方式:
#include <iostream> using namespace std; class Node { public: int data; Node* link; Node(int val) : data(val), link(nullptr) {} // 构造函数初始化节点 }; class LinkedList { private: Node* head; // 用指针指向头节点 public: LinkedList(int a) { head = new Node(a); // 动态创建头节点 } void insert(int data) { Node* newNode = new Node(data); // 动态分配新节点 newNode->link = head; // 新节点指向当前头节点 head = newNode; // 更新头节点为新节点 } void display() { Node* current = head; // 用指针遍历链表 while (current != nullptr) { // 遍历到尾节点结束 cout << current->data << endl; current = current->link; // 移动到下一个节点 } } // 析构函数,释放所有节点内存,避免泄漏 ~LinkedList() { Node* temp; while (head != nullptr) { temp = head; head = head->link; delete temp; } } }; int main() { LinkedList obj(20); obj.insert(30); obj.insert(40); obj.display(); return 0; }
无指针版本(用索引代替指针)
如果坚持避免使用节点指针,可以用数组存储节点,用索引代替指针实现链表,但这种方式链表长度固定,扩展性有限:
#include <iostream> using namespace std; const int MAX_SIZE = 100; // 预先设定最大节点数 class Node { public: int data; int link; // 用索引表示下一个节点,-1代表空 Node() : data(0), link(-1) {} }; class LinkedList { private: Node nodes[MAX_SIZE]; int head; // 头节点的索引 int freeIndex; // 空闲节点的起始索引 public: LinkedList(int a) { // 初始化空闲节点链表 for (int i = 0; i < MAX_SIZE - 1; ++i) { nodes[i].link = i + 1; } nodes[MAX_SIZE - 1].link = -1; freeIndex = 0; // 创建头节点 head = freeIndex; freeIndex = nodes[freeIndex].link; nodes[head].data = a; nodes[head].link = -1; } bool insert(int data) { if (freeIndex == -1) { cout << "链表已满,无法插入新节点" << endl; return false; } // 分配空闲节点 int newNodeIndex = freeIndex; freeIndex = nodes[freeIndex].link; nodes[newNodeIndex].data = data; nodes[newNodeIndex].link = head; head = newNodeIndex; return true; } void display() { int current = head; while (current != -1) { cout << nodes[current].data << endl; current = nodes[current].link; } } }; int main() { LinkedList obj(20); obj.insert(30); obj.insert(40); obj.display(); return 0; }
内容的提问来源于stack exchange,提问作者EclipsedProgram
相关产品推荐
相关产品推荐

