单链生成问题 创建不了单链 你什么问题??
#include <iostream>
using namespace std;
typedef struct Node{
int data;
struct Node *next;
} LNode;
int creat(LNode *&h,int n)
{
int i;
LNode *p,*s;
h=NULL;
p=(LNode*)malloc(sizeof (LNode));
p=h;
if(!p)
{
cout<<"生成结点错误"<<endl;
}
p->data=1;
h=p;
for(i=2;i<=n;i++)
{
s=(LNode *)malloc(sizeof (LNode));
s->data=i;
p->next=s;
p=p->next;
p=s;
}
p->next=h;
return 1;
}
void traver(LNode *h)
{
LNode *p=h;
cout<<p->data<<" ";
p=p->next;
while(p!=h)
{
cout<<p->data<<" ";
p=p->next;
}
}
void main()
{
LNode *h;
int n;
cout<<"请输入:要创建多少个数"<<endl;
cin>>n;
creat(h,n);
traver(h);
}
[解决办法]
- C/C++ code
int creat(LNode *&h,int n){ int i; LNode *p,*s; h=NULL; p=(LNode*)malloc(sizeof (LNode)); //p=h;不要 if(!p) { cout<<"生成结点错误"<<endl; } p->data=1; h=p; for(i=2;i<=n;i++) { s=(LNode *)malloc(sizeof (LNode)); s->data=i; p->next=s; p=p->next; //p=s;不要 } p->next=h; return 1;}
[解决办法]
#include <iostream>
#include <malloc.h>
using namespace std;
typedef struct node
{
int num; //数值域
struct node *next; //指针域
}stud;
stud* Create(int n)
{
//head:用来指向链表的头部。链表需要一个指针来标识链表,这就是头指针。
//p1:用来指向新结点,以及用来遍历链表的每一个结点。
//p2:用来指向当前结点
stud *head,*p1,*p2;
head=p1=p2=NULL;
for(int i=0;i<n;i++)
{
p1=(stud*)malloc(sizeof(stud));
p1->num=i;
if(i==0)
{
head=p1;
}
else
{
p2->next=p1;
}
p2=p1;
}
p2->next=NULL;
return head;
}
void TraverStud(stud *head)
{
if(!head)
{
return ;
}
stud *p=head;
do{
cout<<p->num<<"\t";
p=p->next;
}while(p != NULL);
cout<<endl;
}
int main()
{
int n;
cout<<"Please input the number of node:";
cin>>n;
stud *head=Create(n);
TraverStud(head);
return 0;
}
运行结果:
Please input the number of node:8
0 1 2 3 4 5 6 7