c++双指针的表现形式
如何用用c++的语言风格,实现双指针的表达
判断链表是否有环
ListNode*slow=head;
ListNode*fast=head;
while(fast!=nullptr)
{
fast=fast->next;
if(fast!=nullptr)
{
fast=fast->next;
}
if(fast==slow)
{
return true;
}
slow=slow->next;
}
return nullptr;
class Node
{
public:
Node * prev;
Node * next;
ElemType data;
};
#include <iostream>
using namespace std;
struct teacher {
int id;
char name[64];
};
int tea(struct teacher* &a) {//指针引用,a是c的别名
a = (struct teacher*)malloc(sizeof(struct teacher));//a = 开辟的内存,相当于c开辟内存,在写入数据
if (a == NULL)
{
return -1;
}
a->id = 100;
strcpy_s(a->name, "礼仪");
return 0;
}
int tea1(struct teacher **a) {//指向指针的指针指向a(函数的实参)指针的取地址
struct teacher *t = NULL;//a=实参的取地址,&a是a(指向指针的指针)的取地址,*a是a指向内存的内容
if (a==NULL)
{
return -1;
}
t = (struct teacher*)malloc(sizeof(struct teacher));//理解为某指针指向某地址,指针t = 某指针
//cout << t << endl;//t是一个指针,指向在内存中开辟的一个地址,t=某地址
//cout << &t << endl;//&t是t自己的取地址
//cout << a << endl;//
//cout << *a << endl;
//cout << &a << endl;
//cout << &(*a) << endl;
t->id = 100;
strcpy_s(t->name, "哈哈");
*a = t;
return 0;
}
void rea1(struct teacher **a) {
if (a==NULL)
{
return;
}
struct teacher* t = *a;
if (t!=NULL)
{
free(t);//开辟内存,要释放
*a = NULL;
}
}
void rea(struct teacher *&a) {
if (a==NULL)
{
return;
}
else
{
free(a); //开辟内存,要释放
a = NULL;
}
}
void main() {
struct teacher *c = NULL;//定义一个指针作传输体
tea1(&c);
cout << "id=" <<c->id<<"名字:"<< c->name << endl;//极有可能是*(c->id)
rea1(&c);
tea(c);
cout<< "id=" <<c->id<<"名字:"<< c->name << endl;
rea(c);
}
效果图:
双指针是一种常见的算法技巧,用于在数组或链表中进行快速的查找、遍历或操作。在C++中,可以使用指针来实现双指针的表达。
下面是一个示例代码,演示了如何使用语言风格实现双指针:
#include <iostream>
using namespace std;
int main() {
int nums[] = {1, 2, 3, 4, 5};
int* left = nums; // 左指针指向数组的第一个元素
int* right = nums + 4; // 右指针指向数组的最后一个元素
while (left < right) {
cout << *left << " " << *right << endl;
left++;
right--;
}
return 0;
}
在这个示例中,我们声明了一个整数数组nums
,然后使用一个整型指针left
指向数组的第一个元素,使用另一个整型指针right
指向数组的最后一个元素。
接下来,我们使用一个循环来遍历数组,每次循环中,输出左指针和右指针所指向的元素,并将左指针向右移动一位,右指针向左移动一位。
执行以上代码,会输出以下结果:
1 5
2 4
这个示例代码展示了如何使用指针来实现双指针的表达,通过不断移动指针来完成元素遍历或操作。
注意:在实际的编程中,双指针并不局限于数组,也可以使用在其他数据结构如链表中,只需要根据具体的情况来定义指针的类型和操作。