You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++双向链表相邻元素交换函数异常,请求修正实现

C++双向链表swapAdjacent()函数修正方案

你的问题出在swapAdjacent()函数的指针更新逻辑和遍历步进上:当前代码仅正确处理了第一组相邻元素的交换,后续组的交换因指针指向错误或遍历位置错误,导致链表结构混乱,无法完成预期的两两交换。

错误分析

常见的错误原因包括:

  • 交换后未正确更新所有关联的prev和next指针,导致后续遍历的节点链断裂。
  • 遍历步进错误,交换后未定位到下一组的起始节点,而是重复处理已交换的节点。

修正后的完整代码

#include <iostream>

struct Node {
    int data;
    Node* prev;
    Node* next;
    Node(int val) : data(val), prev(nullptr), next(nullptr) {}
};

class DoublyLinkedList {
private:
    Node* head;
public:
    DoublyLinkedList() : head(nullptr) {}
    
    void addNode(int val) {
        Node* newNode = new Node(val);
        if (!head) {
            head = newNode;
            return;
        }
        Node* temp = head;
        while (temp->next) {
            temp = temp->next;
        }
        temp->next = newNode;
        newNode->prev = temp;
    }
    
    void printList() {
        Node* temp = head;
        while (temp) {
            std::cout << temp->data << "\t";
            temp = temp->next;
        }
        std::cout << std::endl;
    }
    
    void swapAdjacent() {
        Node* current = head;
        while (current != nullptr && current->next != nullptr) {
            Node* node1 = current;
            Node* node2 = current->next;
            
            // 断开node1与node2的连接,将node1指向node2的下一个节点
            node1->next = node2->next;
            if (node2->next != nullptr) {
                node2->next->prev = node1;
            }
            
            // 将node2连接到node1的前一个节点
            node2->prev = node1->prev;
            if (node1->prev != nullptr) {
                node1->prev->next = node2;
            } else {
                // 若node1是头节点,更新链表头为node2
                head = node2;
            }
            
            // 建立node2与node1的新连接
            node2->next = node1;
            node1->prev = node2;
            
            // 步进至下一组的起始节点(原node2的下一个节点)
            current = node1->next;
        }
    }
};

int main() {
    DoublyLinkedList dll;
    dll.addNode(7);
    dll.addNode(-8);
    dll.addNode(3);
    dll.addNode(12);
    dll.addNode(4);
    dll.addNode(8);
    
    std::cout << "原始链表: ";
    dll.printList();
    
    dll.swapAdjacent();
    
    std::cout << "交换后链表: ";
    dll.printList();
    return 0;
}

关键修正点

  1. 明确节点拆分:将当前节点和其下一个节点分别赋值给node1和node2,避免指针操作时的混淆。
  2. 完整指针更新:不仅处理节点间的直接连接,还更新了node2->next的prev指针和node1->prev的next指针,确保链表结构完整。
  3. 正确遍历步进:交换完成后,将current移动到node1->next(即原node2的下一个节点),保证下一次循环处理的是下一组未交换的相邻元素。

运行上述代码后,原始链表7 -8 3 12 4 8会被转换为预期的-8 7 12 3 8 4。

内容的提问来源于stack exchange,提问作者Wadah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 05:53:31