求大神帮我看看我的代码,我调试的时候在zhu'han'shu'zhong这个Find函数并没有调用!
#include<iostream>
using namespace std;
typedef int ElemType;
struct LNode {
ElemType data;
LNode* next;
};
//链表的输入
LNode* Create(void)
{
cout << "请输入数据:" << endl;
LNode* head, * p1, * p2;
int i = 0;
p1 = p2 = new LNode;
cin >> p1->data;
head = NULL;
while (p1->data!=0)
{
i++;
if (i == 1)
head = p1;
else
p2->next = p1;
p2 = p1;
p1 = new LNode;
cin >> p1->data;
}
p2->next = NULL;
return head;
}
LNode* Find(int k, LNode* head)
{
LNode* p = head;
int i = 1; //第一个结点
while (p != NULL && i < k) //链表不为空并且还没找到第k个结点
{
p = p->next;
i++;
}
if (i == k) return p; //找到了
else return NULL; //没找到
}
int main()
{
LNode* p;
p = Create();
int n=2;
Find(n, p); //并没有调用!!
cout << p->data << endl;
}
Find(n, p);
cout << p->data << endl;
->
LNode* p1 = Find(n, p);
cout << p1->data << endl;
大致看了一下你的程序,程序写的没问题,find函数也调用了,但是你没有把返回的指针赋值给p,最后一句cout << p->data << endl;自然输出不了数据。建议以后可以设置断点测试哪里出问题。
#include<iostream>
using namespace std;
typedef int ElemType;
struct LNode {
ElemType data;
LNode* next;
};
//链表的输入
LNode* Create(void)
{
cout << "请输入数据:" << endl;
LNode* head, * p1, * p2;
int i = 0;
p1 = p2 = new LNode;
cin >> p1->data;
head = NULL;
while (p1->data!=0)
{
i++;
if (i == 1)
head = p1;
else
p2->next = p1;
p2 = p1;
p1 = new LNode;
cin >> p1->data;
}
p2->next = NULL;
return head;
}
LNode* Find(int k, LNode* head)
{
LNode* p = head;
int i = 1; //第一个结点
cout<<"hhhh";
while (p != NULL && i < k) //链表不为空并且还没找到第k个结点
{
p = p->next;
i++;
}
if (i == k) return p; //找到了
else return NULL; //没找到
}
int main()
{
LNode* p;
p = Create();
// while(p)
// {
// cout<<p->data;
// p=p->next;
// }
int n=2;
p=Find(n, p); //并没有调用!!
cout<<"ppppp";
cout << p->data << endl;
}