C++,学习链表



我正在学习一个非常简单的链表,
但下面的代码不起作用,当我输入1和2时,系统输出只有1和NULL
有人能帮帮我吗
这是我的密码。

#include <iostream>  
using namespace std;  
struct node  
{  
    char username[10];  
    node *next;  
};  

int main()  
{  
    node *head;  
    node *place;  
    node *tail;  
    head = new node;  
    place = head;  
    tail = place->next;  
    cout<<"username 1 ";  
    cin>>place->username;  
    place = tail;  
    place = new node;  
    tail = place->next;  
    cout<<"username 2 ";  
    cin>>place->username;  
    place = head;  
    cout<<"username 1 ";  
    cout<<place->username<<endl;  
    place = place->next;  
    cout<<"username 2 ";  
    cout<<place->username<<endl;  

    return 17;  
}  

如有任何帮助,我们将不胜感激,谢谢。

从不将节点链接在一起。在整个程序中,没有任何地方设置下一个字段。把这个写在纸上,一次一句。而不是

place = new node;  
tail = place->next;

创建新节点时,将其添加到列表的末尾:将当前末端链接到新节点,然后移动末端指针。

place = new node;  
tail->next = place;
tail = place;
#include <iostream>  
using namespace std;  
struct node  
{  
    char username[10];  
    node *next;  
};  

int main()  
{  
    node *head;  
    node *place;  
    node *tail; 
    place = new node;  
    head = place;      // head is assigned to the first created place and should never be modified ever after.
    tail = head;      // at the beginning the last element is also the first, it will move along and always point to the last node created

    cout<<"username 1 ";  
    cin>>place->username;

    place = new node;    // create new node
    tail->next = place;  // assign next
    tail = place;        // then point the tail to the new node
    cout<<"username 2 ";  
    cin>>place->username;  
    place = head;      // rewind the list to the head
    cout<<"username 1 ";  
    cout<<place->username<<endl;  
    place = place->next;  
    cout<<"username 2 ";  
    cout<<place->username<<endl;  

    return 17;  
}  

相关内容

  • 没有找到相关文章