我正在学习一个非常简单的链表,
但是下面这段代码不起作用,当我输入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;
}
感谢您的任何帮助,谢谢。
答案 0 :(得分:1)
您永远不会将节点链接在一起。 在整个程序中没有任何地方设置 next 字段。 在纸上解决这个问题,一次一个声明。 而不是......
place = new node;
tail = place->next;
创建新节点时,将其添加到列表末尾:将当前节点链接到新节点,然后移动结束指针。
place = new node;
tail->next = place;
tail = place;
答案 1 :(得分:1)
#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;
}