求大神,帮忙看下用类实现的单链表解决方案
求大神,帮忙看下用类实现的单链表
以下程序编译时总是提示主函数总的p没有初始化,运行结果弹出停止
------解决方案--------------------
int main()
{
Node *p;
Node *q;
p->Create();
q = p->Create();
p->length(q);
p->Print(q);
cout<<endl;
return 0;
}
Node *p;这只是声明了一个指针变量而已,不是具体的对象,LZ你还要深刻理解一下C语言的指针。好好看看书,理解什么是指针。
以下程序编译时总是提示主函数总的p没有初始化,运行结果弹出停止
/*********实现一个单链表的建立、测长、打印***********/
#include <iostream>
#include <iomanip>
using namespace std;
class Node
{
public:
Node();
~Node();
Node* Create();//单链表的建立
int length(Node*);//求单链表的长度
void Print(Node*);//打印单链表
private:
int data;
Node* next;
};
Node::Node()
{
data = 0;
next = NULL;
}
Node::~Node()
{
}
Node* Node::Create()
{
Node *head;//头指针
Node *p,*q;
head = (Node*)malloc(sizeof(Node));
p = head;
int flag = 1;
int x;
while(flag)
{
cout<<" Input x data: ";
cin>>x;
if(x != 0)
{
q = (Node*)malloc(sizeof(Node));
q->data = x;
cout<<"Output data: "<<q->data<<endl;
p->next = q;//将q插在p的后面
p = q;//p是记录插入的位置
}
else
flag = 0;
}
head = head->next;
p->next = NULL;
cout<<"the head of linked list is: "<<head->data<<endl;
return head;
}
int Node::length(Node *head)
{
int n = 0;
Node *p;
p = head;
while(p != NULL)
{
p = p->next;
n++;
}
return n;
}
void Node::Print(Node *head)
{
Node *p;
p = head;
int n;
n = length(head);//表的长度
cout<<"Output the length of linked list is: "<<n<<endl;
while(p != NULL)
{
cout<<setw(2)<<p->data;
p = p->next;
}
}
int main()
{
Node *p;
Node *q;
p->Create();
q = p->Create();
p->length(q);
p->Print(q);
cout<<endl;
return 0;
}
------解决方案--------------------
int main()
{
Node *p;
Node *q;
p->Create();
q = p->Create();
p->length(q);
p->Print(q);
cout<<endl;
return 0;
}
Node *p;这只是声明了一个指针变量而已,不是具体的对象,LZ你还要深刻理解一下C语言的指针。好好看看书,理解什么是指针。