c++单链表的查询问题

来源:百度知道 编辑:UC知道 时间:2024/09/21 08:11:41
用c++实现单链表的查询功能,目的是:查询链表中值为x的数据,并且返回这些数据所在的位置(注意,是要把这些数据所在的位置全都返回出来)。下面是我写的程序,不成功,显示乱码,望高手指教。
SingleList.h里:
//find the data x,return x's oposition
template <class T>
int* SingleList<T>::search(const T& x)
{
ListNode<T>* current = head->m_pnext;
int index = 1;
int t = 0;
int aa[10];
while (current)
{
if (current->m_data == x)
{
aa[t]=index;
t++;
}
current = current->m_pnext;
index ++;
}
return aa;
}

main.h里:
SingleList<int> singlelist;
cout << "input the data's value: ";
cin >> value;
int* t;
int i;
t=singlelist.search(value);
cout << value << "'s index is: ";
for (i = 0; i < 2; i++)
{
cout << *(t+i) << "\t";
}

假设链表数据是:1,2,2,3,3
输入2,结果为:2's index is: -858

这样是不行的,原因是:aa[10]是search函数中的局部变量,分配在栈上,其生命周期只存在于search函数执行过程中,所以里面的内容在search函数结束后就不存在了。所以这时候再用指向aa的指针t也不能再正确获取其内容了。
建议把aa[10]写成SingleList的成员变量,再提供相应的访问接口,这样就可以在类外访问了,其生命周期与保存aa[10]的对象一致。

cout << a[i] << "\t"; 不就好了