在c++中交换指针

Swap the pointer in C++

本文关键字:指针 交换 c++      更新时间:2023-10-16

最近我正在学习c++中的链表。下面是我的代码:

#include <iostream>
using namespace std;
class Node{
    Node* next;
    int num;
public:
    Node(int num){
        this->num = num;
    }
    void connect(Node* next){
        this->next = next;
    }
    Node* next_node(){
        return next;
    }
    void COUT(){
        cout<<this->num<<endl;
    }
};

void swap(Node* n1,Node* n2){
    static Node* n = n1;
    n1 = n2;
    n2 = n;
}
class List{
    Node* head;
    Node* last;
public:
    List(){
        head = 0;
        last = 0;
    }
    void insert(Node* n){
        if(head==0){
            head = n;
            last = n;
        }
        else{
           last->connect(n);
           last = n;
        }
    }
    void swap_head_last(){
        swap(head,last);
    }
};



int main()
{
    List* LL = new List();
    for(int i=0;i<10;i++){
        LL->insert(new Node(i));
    }
    LL->swap_head_last();

    return 0;
}

没有错误,直到我试图使"无效swap_head_last()"。我想在这个函数中做的是使指针"*head"指向列表的末尾,并使指针"*last"指向列表的开始。

但是当我试图在调用这个函数后打印这两个指针的值时,我发现它们仍然指向同一个对象。

我检查了这两页,

交换两个指针

c++交换指针

但是我想要改变的是这两个指针的方向,而不是指针指向的对象的值。

我知道如果我修改这个函数如下:

void swap_head_last(){
    static Node* n = head;
    head = last;
    last = n;
}

结果应该是正确的。

这个函数有什么问题?

根本问题在于您不能轻松地交换单链表中的节点。实际上,问题是当移动一个节点从它的位置时,必须修改前一个节点的后继节点。

此外,您尝试实现swap什么也不做,它只是交换两个局部变量(一旦函数完成,这将被忘记)。

你可以使用引用来交换:

void swap(Node*& n1, Node*& n2)
{
    Node* n = n1;
    n1 = n2;
    n2 = n;
}

但正如所指出的,这仍然会留下只有headlast将被交换的问题。倒数第二个元素的后继元素仍然是旧的最后一个元素,您也必须更新该指针

试试这个:

void swap(Node** n1,Node** n2){
    Node* n = *n1;
    *n1 = *n2;
    *n2 = n;
}

Explination:如果需要交换两个整数,则需要void swap(int*, int*)。

因此,如果你需要交换指针,你需要void swap(int**, int**)。

一开始不是很直观