cpp
#include<iostream> using namespace std; struct node { char data; node *next; }; ;node *Create(); ;void show(node *head); int main() { node *head; head=Create(); show(head); return 0; } node *Create() { char temp; node *head=NULL; node *next=NULL; node *r=head; node *PS; cout<<"请输入"<<endl; while(temp!='*') { cin>>temp; PS=new node; PS->data=temp; PS->next=NULL; if(head==NULL) { head=PS; } else { r->next=PS; } r=PS; } return head; } void show(node *head) { node *read=head; while(read!=NULL) { cout<<read->data; read=read->next; } cout<<endl; }
把r=PS移动到else里面为什么不行啊
就是C++
else
{
r->next=PS;
r=PS;
}
求教!谢谢。。
放到外面说明当
head == NULL
成立的时候也需要执行r = PS
。那么为什么每次增加节点都需要执行r = PS
呢?你顺着逻辑想想吧。。好吧,其实是这样的,按你的想法放到里面,增加第一个节点的时候
head == NULL
成立,r = PS
并不会执行,那么第二次增加节点的时候r
还是等于NULL
但head == NULL
不成立,于是执行r->next = PS
时程序挂掉。。r
这个指针其实指向的是当前链表最后一个节点。PS..申明node结构的时候应该是
node *next
吧。。。