64,632
社区成员
发帖
与我相关
我的任务
分享
Node*& getp(int pos)
{
if(pos<0||pos>=len)
pos=len;
if(pos==0)
return head;
if(head==NULL)
return head;
Node* p = head;
for(int i=0;i<pos-1;i++)
p=p->next;
return p->next;
}
bool insert(T d,int pos=0)
{
Node* nd = new Node(d);
Node* &p = getp(pos); //这一句为什么要*p的引用
nd->next = p;
p = nd;
len++;
return true;
}
List list;
T d;
Node* nd = new Node(d);
list.getp(1) = nd;
Node* getp(int pos) //别返回引用
{
if(pos<0||pos>=len)
pos=len;
if(pos==0)
return head;
if(head==NULL)
return head;
Node* p = head;
for(int i=0;i<pos-1;i++)
p=p->next;
return p;
}
bool insert(T d,int pos=0)//这个函数要判断下以防止getp返回NULL
{
Node* nd = new Node(d);
Node* p = getp(pos);
if(p == NULL){
head = nd;
head->next = NULL;
}
else{
nd->next = p->next;
p->next = nd;
}
len++;
return true;
}
Node* &p = getp(pos); //这一句为什么要*p的引用
如果不是引用的话,getp返回的是一个指针的副本,这么说吧:
int* p = NULL;
int*& fun()
{
p = new int;
return p;
}
int* pp = fun();
*pp = 10;
pp = new int();
*pp = 100;//这个之后,*p=10;
如果:
int*& pp = fun();
*pp = 10;
pp = new int();
*pp = 100;//这个之后,*p=100;
#include <iostream>
using namespace std;
typedef int T;
class List
{
struct Node
{
T data;
Node* next;
Node(T data=T()):data(data),next(NULL){}
};
Node* head;
int len;
public:
List():head(NULL),len(0)
{
}
Node*& getp(int pos)
{
if(pos<0||pos>=len)
pos=len;
if(pos==0)
return head;
if(head==NULL)
return head;
Node* p = head;
for(int i=0;i<pos-1;i++)
p=p->next;
return p->next;
}
bool insert(T d,int pos=0)
{
Node* nd = new Node(d);
Node* p = getp(pos);
nd->next = p;
p = nd;
len++;
return true;
}
void travel()
{
Node* p = head;
cout << "[ ";
while(p!=NULL)
{
cout << p->data << ' ' ;
p=p->next;
}
cout << "]" << endl;
}
void clear()
{
Node*p = head;
while(p!=NULL)
{
p=p->next;
delete head;
head=p;
}
len=0;
head=NULL;
}
~List()
{
clear();
}
};
int main()
{
List lst;
lst.insert(1);
lst.insert(2);
lst.insert(3);
lst.insert(4);
lst.insert(5,-1);
lst.travel();
return 0;
}