双向链表中如何实现新节点插入到当前节点的前驱位置?
解决双向链表命令处理的问题
你的核心问题在于没有维护当前光标位置的跟踪指针,每次执行A命令都直接把节点追加到链表末尾,而且完全没实现B命令的光标回退逻辑,所以得不到期望的123输出。下面是具体的修改方案和代码:
关键修改点
- 新增
currentCursor指针,专门跟踪当前光标所在的位置(光标默认在表头节点之后,也就是第一个可插入位置) - 删除每次循环里强制跳到链表末尾的冗余代码
- 实现
B命令的光标回退逻辑 - 修改
A命令的插入逻辑,在光标位置后插入新节点,并更新光标位置
修改后的完整代码
#include <iostream> #include <string> #include <fstream> using namespace std; class Node { public: char letter; Node* next; Node* prev; Node(char cc) { letter = cc; next = prev = nullptr; } }; string command; char parameter; Node* rows[10]; int currentRow = 0; Node* currentCursor; // 新增:跟踪当前光标位置 int main() // C++标准要求main必须返回int,不能用void { for (int i = 0; i < 10; i++) { rows[i] = new Node('.'); rows[i]->next = nullptr; rows[i]->prev = nullptr; } currentCursor = rows[currentRow]; // 初始化光标到当前行的表头节点 ifstream input("c:\\temp\\input.txt"); while (input >> command) // 直接用输入流判断,比peek更可靠 { if (command == "B") { // 光标回退:只要不是表头节点,就往前移一位 if (currentCursor != rows[currentRow]) { currentCursor = currentCursor->prev; } } else if (command == "F") { // 光标前进:只要不是最后一个节点,就往后移一位 if (currentCursor->next != nullptr) { currentCursor = currentCursor->next; } } else if (command == "A") { input >> parameter; Node* newnode = new Node(parameter); // 在currentCursor和它的next节点之间插入新节点 newnode->next = currentCursor->next; newnode->prev = currentCursor; if (currentCursor->next != nullptr) { currentCursor->next->prev = newnode; } currentCursor->next = newnode; // 插入后光标移到新节点,下次插入会在新字符后面 currentCursor = newnode; } } input.close(); // 显示链表内容 cout << endl; Node* t = rows[currentRow]->next; while (t != nullptr) { cout << t->letter; t = t->next; } cout << endl; // 释放内存,避免内存泄漏(可选但推荐) for (int i = 0; i < 10; i++) { Node* temp = rows[i]; while (temp != nullptr) { Node* next = temp->next; delete temp; temp = next; } } return 0; }
逻辑验证
执行你的命令序列:
A 1:在表头后插入1,光标移到1节点A 3:在1后插入3,光标移到3节点B:光标回退到1节点A 2:在1后插入2,光标移到2节点
最终链表结构为:表头→1→2→3,输出123,完全符合期望。
内容的提问来源于stack exchange,提问作者Kevin Villamizar
相关产品推荐
相关产品推荐

