在c++中交换指针
Swap the pointer in C++
最近我正在学习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;
}
但正如所指出的,这仍然会留下只有head
和last
将被交换的问题。倒数第二个元素的后继元素仍然是旧的最后一个元素,您也必须更新该指针
试试这个:
void swap(Node** n1,Node** n2){
Node* n = *n1;
*n1 = *n2;
*n2 = n;
}
Explination:如果需要交换两个整数,则需要void swap(int*, int*)。
因此,如果你需要交换指针,你需要void swap(int**, int**)。
一开始不是很直观
相关文章:
- 共享指针的复制和交换效率
- 如何在单个链表中交换两个节点的位置,只修改指针
- 以原子方式交换指针与 nullptr
- 使用指针交换整数
- 使用指针 c++ 交换结构数组中的元素
- 使用指针交换数组的内容
- 无法使用指针写入交换
- 使用指针交换而不引用数组C++
- 共享指针交换方法标识更改
- 为什么基于指针交换两个值在函数范围之外不起作用?
- 将指针交换为指针
- 使用双向链表中的指针交换节点
- 使用指针交换字符变量
- 通过 xor 运算符使用引用或指针交换两个变量的值
- 指针交换怪异
- 当数组是类的数据成员时,如何使用指针交换数组
- 使用公用指针交换指向已分配内存的指针
- 使用指针交换两个字符串会输出奇怪的输出
- 仅通过操作指针交换链表中的相邻节点
- 使用指针交换两个变量