C++创建链表问题

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; }
求教!谢谢。。

阅读 3.5k
2 个回答

放到外面说明当head == NULL成立的时候也需要执行r = PS。那么为什么每次增加节点都需要执行r = PS呢?你顺着逻辑想想吧。。

好吧,其实是这样的,按你的想法放到里面,增加第一个节点的时候head == NULL成立,r = PS并不会执行,那么第二次增加节点的时候r还是等于NULLhead == NULL不成立,于是执行r->next = PS时程序挂掉。。

r这个指针其实指向的是当前链表最后一个节点。

PS..申明node结构的时候应该是node *next吧。。。

node *head=NULL;
node *next=NULL;
node *r=head;

此时r=NULL, 然后

r->next=PS;
r=PS;

相当于

NULL->next=PS
...

然后大家就呵呵了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题