#include <iostream>
using namespace std;
struct node{
int val;
node* previous;
node* next;
void init(int n){
val = n;
previous = NULL;
next = NULL;
}
}*head;
//指针的引用
// head->neck->tail
void func(node* &p){
if(p->next == NULL){
return;
}
if(p->val == 2){
cout<<"p is neck"<<endl; //最开始p为neck
p->previous->next = p->next; //将head的next指针指向tail,表面上p没有改变;
// 然而实质上也改变了p,因为p=head->next,此时p指向的是tail
if(p->val == 3)
cout<<"p is tail"<<endl; //p改为tail
p->next->previous = p->previous; //试图将tail的previous指针指向head,然而此时p为tail,p->next = NULL,报错
}else{
func(p->next);
}
}
int main(){
head = new node;
head->init(1);
head->next = new node;
node* neck = head->next;
neck->init(2);
neck->previous = head;
neck->next = new node;
node* tail = neck->next;
tail->init(3);
tail->previous = neck;
func(head);
delete head;
delete neck;
delete tail;
return 0;
}
使用引用类型时要小心谨慎。