//你的原程序中在插入数的时候,没设置head,所以head一直为null,则while循环p的值初始就为null,所以不会有任何输出。况且运行的话会出现运行时错误,因为rear的初值为null,i=1的时候,rear=null,这时候调用rear->next程序会报错退出,所以应该先判断rear是否为空,即判断表中是否有元素,没有元素的话,就应该将第一个插入的元素设为rear,同时也要设为head。head=rear=p表示head = prear = p第二次插入的时候head仍然指向头元素,rear指向新元素。判断使用head和rear效果是一样的。
struct增加一个构造函数,for循环的逻辑改了一下
#include <iostream>
using namespace std
struct inode
{
inode(int i) : data(i), next(null) {}
int data
inode*next
}
int main()
{
int m=8, n = 4
inode *head = NULL, *rear = NULL
for(int i=1i<=ni++)
{
inode *p = new inode(i)
(rear == NULL ? head : rear->next) = p
rear=p
}
inode *p = head
while(p!=NULL)
{
cout<<p->data<<endl
p=p->next
}
return 0
}
void Create(Node *&tail)//尾插法
{
Node *p
int x
tail =NULL
cout<<"输入数据,以输入-1结束输入:"
cin>>x
while(x!=-1)
{
p=new Node
p->data=x
tail=p->next//p->next指向tail ,则tail插入到链表里
p=p->next //将p移动到新节点的位置
p->next=NULL//然后将让节点的下一个位置为空结点
cout<<"输入数据,以输入-1结束输入:"
cin>>x
}
你的语句是
{p->next=NULL
tail=p
tail->next =p}
p是指向当前结点的,tail是新的结点,按照你的意思是,p->next=NULL,P的下一个结点为空,p到tail的位置,这儿你就出错了,p这个指针到了tail的位置,可是tail和前一个指针有什么关系呢,这个链表就断了,没有连接上,然后你还让p指向新节点的next干什么,
DataP add(int i,DataP last){
DataP newp
if((newp = (DataP)malloc(sizeof(Data))) == NULL){
fprintf(stderr,"data allocation error !\n")
exit(1)
}
newp ->val =i
last->pointer=newp
return newp
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)