在c++中打印链表的元素(参见代码)
To print elements of Link List in c++ (See Code)
我的问题是,我试图使一个程序,将使节点(链接列表)动态。一切都很好,但是当我在底部尝试使用while循环打印链接列表的元素时:while(ptr->next !=NULL)
,程序只打印第一个元素。(是的,我在循环中提到了ptr=ptr->next
)下面是我的CODE:
struct node {
int item;
node *next;
}
;
main() {
int a,b,c=0;
node *head,*tail,*ptr, *temp;
ptr = new node;
ptr->item = 0;
ptr->next = NULL;
head= ptr;
ptr->next=tail;
for (int i=0;1;i++) {
cout<<" Enter 1 if u want to make another noden Enter 2 to stop making nodesn";
cin>>a;
if(a==1) {
if(c!=0) {
ptr = new node;
cout<<"Enter new element at the new node:n";
cin>>b;
ptr->item = b;
ptr->next = NULL;
tail = ptr;
}
if(c==0) {
ptr = new node;
cout<<"Enter new element at the new node:n";
cin>>b;
ptr->item = b;
head->next= ptr;
ptr->next = NULL;
tail = ptr;
c++;
}
} else if(a==2) {
break;
}
}
ptr=head;
while(ptr->next != NULL) {
ptr=ptr->next;
cout<<" element: "<<ptr->item<<endl;
}
}
我的编译器(带有flag -Wall -Wextra -pedantic的g++ 4.8)已经解决了这个问题:
warning: ‘tail’ is used uninitialized in this function [-Wuninitialized]
你正在更新下一个,但有一个未初始化的变量尾部
最初希望将尾部设置为与头部相同的节点。这是因为您希望将元素附加到尾部元素,而不管头部在哪里。这也消除了计算是否添加了一个节点(变量c
)的复杂性,并消除了条件分支(其中代码非常相似:参见DRY)
向链表尾部添加元素的过程如下:
- 填充新元素,将其
next
设置为NULL
。 - 将尾元素指向新元素的旁边。
- 将新元素设置为尾部
尝试使用这个
struct node {
int item;
node *next;
};
main() {
int input;
node *head,*tail,*ptr;
ptr = new node;
ptr->item = 0;
ptr->next = NULL;
head = ptr;
tail = ptr;
while(true) {
cout<<" Enter 1 if u want to make another noden Enter 2 to stop making nodesn";
cin>>input;
cin.clear();
if(input==1) {
ptr = new node;
cout<<"Enter new element at the new node:n";
cin>>input;
cin.clear();
ptr->item = input;
tail->next= ptr;
ptr->next = NULL;
tail = ptr;
} else if(input==2) {
break;
}
}
ptr=head;
while(ptr->next != NULL) {
ptr=ptr->next;
cout<<" element: "<<ptr->item<<endl;
}
}
相关文章:
- 用于查找数组中最大元素的出现次数的代码,给出分段错误
- 我的选择排序代码是否存在导致它跳过数组中的元素的问题?
- 代码是否有效.如果我想显示第一个元素?如果不是,那么 s.begin() 会返回什么?
- 为什么这段代码给出错误......'a'是指针到字符指针,应该存储's'的地址,因为s是指向数组的第一个元素的指针
- 我可以在一行代码中将向量中与条件匹配的所有元素插入到集合中吗?
- 我写了这个简单的代码,应该计算一系列数组元素的最高数量,但结果很奇怪
- 在此C++代码中,迭代器引用列表的哪个元素?
- 我用于汇总数组元素的 c++ 代码无法正常工作
- 迭代列表以查找元素的出现.代码问题
- 为什么代码无法打印此 2D 数组的元素?
- 我已经编写了一个代码来查找数组元素的反向,但它没有给出所需的输出
- 为什么此C 代码不起作用 - 试图删除集合中的元素时,请参考错误
- 我的C 代码在尝试计算表中元素的总和时崩溃
- 元素向量乘法 C++(代码不起作用)
- 编写一个代码,该代码在给定的链表中将删除具有奇数值的元素
- 如何让我的代码从矩阵输出非零元素
- 试图用c++编写我自己的链表实现,在点击列表中的3个元素后编写segfault代码
- 使用函数优化数组中的代码最大元素
- 将未使用的元素添加到C/C 结构加快并减慢代码执行
- 我的代码正在制作 2D 数组元素的重复副本.代码中有什么问题?