为什么我的链表的输出只从第二个输入开始



当我运行此代码并将数据输入到链接列表中时,如下所示:

23 45 55

输出为:

45 55

第一个数据丢失了!!!!

怎么了?如何更改代码以获得正确的输出?

#include<iostream>
using namespace std;
struct node
{
int data;
node* next;
};
int main()
{
char ch;
node* n;
node* t;
node* h;
n= new node();
t=n;
h=n;
cout<<"Linked list is created.Now You can write data into it."<<endl;
cout<<"Enter data into the linked list:";
cin>>t->data;
cout<<"do you want to enter more data into the linked list?(y/n):";
cin>>ch;
if( ch =='y'|| ch =='Y')
do
{
n=new node();
t->next=n;
cout<<"Enter data into the linked list:";
cin>>t->data;
t=t->next;
cout<<"do you want to enter more data into the linked list?(y/n):";
cin>>ch;
}while(ch=='Y'||ch=='y');

t->next=NULL;
cout<<endl;
cout<<endl;
cout<<endl;
cout<<"================================="<<endl;
cout<<endl;
cout<<endl;
cout<<endl;

cout<<"Do you want to print data on the linked list?(y/n):";
cin>>ch;
if(ch=='y'||ch=='Y')
{
t=h;
while(t->next != NULL)
{
cout<<t->data<<endl;
t=t->next;
}
}
}

注释中已经指出了错误。让我补充一下,过于冗长的代码会使这种错误很难被发现。链表创建(无需插入或其他复杂操作(是一个简单的过程,可以(也应该(用简单简洁的代码来表示。

使用问题中的struct node,读取整数直到输入结束,然后打印出来:

int main() {
int data;
node *list;
node **end{&list};
// build the list
while (std::cin >> data) end = &(*end = new node{.data{data}})->next;
*end = nullptr;
// print the list
for (const node *n{list}; n; n = n->next) std::cout << n->data << 'n';
// delete the list
while (list) {
const node *const previous{list};
list = list->next;
delete previous;
}
}

当你不介意列表有相反的顺序时,它会变得更简单。那么你就不需要指向它的末端:

int main() {
int data;
node *list{};
// build the list
while (std::cin >> data) list = new node{.data{data}, .next{list}};
// print the list
for (const node *n{list}; n; n = n->next) std::cout << n->data << 'n';
// delete the list
while (list) {
const node *const previous{list};
list = list->next;
delete previous;
}
}

相关内容

  • 没有找到相关文章

最新更新