#include<iostream>
using namespace std;
struct node{
int data; // structure for each node of list
node *p;
};
class LinkedList{
node *head,*tail;
public:
LinkedList(){ //empty LinkedList used for overall structure
head=NULL;
tail=NULL;
}
void addnode(int x);
void show();
};
void LinkedList::addnode(int x){
node *temp=new node;
temp->data=x;
temp->p=NULL;
if(head==NULL){ //linkedList is empty therefore temp is both head and tail now
temp=head;
temp=tail;
}
else{
tail->p=temp;
tail=temp;
}
}
void LinkedList::show(){
node *temp;
temp=head;
while(temp!=NULL){
cout<<endl<<temp->data<<endl;
temp=temp->p;
}
}
int main(){
LinkedList l;
cout<<"Welcome to Linkedlist creation\n";
int choice;
cout<<"To add a node press 1,\nTo view your list press 2\n";
cin>>choice;
switch(choice){
case 1:
int data;
cout<<"Enter the data to be added: ";
cin>>data;
l.addnode(data);
break;
case 2:
l.show();
}
}
请告诉我我的代码有什么问题..!我需要了解我的方法有什么问题......我提到了许多其他来源,大多数和我的一样,但是 show() 根本不起作用......请不要直接转到其他帖子或请告诉在这样做之前我的错误..
编辑:对不起大家的错字,我的意思是相同的 if(head==null) 而不是 =; 我检查了我的代码是否相同,它只是在这里错了,仍然是同样的问题
您LinkedList::addnode
有以下错误:
if(head=NULL){
是错误的。=
是 C++ 中的赋值运算符,它将设置head
为NULL
并将评估为false
。这将有tail->p=temp;
与tail = NULL
它会导致分段错误。temp=head; temp=tail;
也是错的。它正在用某些东西覆盖指向新创建节点的指针,从而造成内存泄漏。功能应该是:
void LinkedList::addnode(int x){
node *temp=new node;
temp->data=x;
temp->p=NULL;
if(head==NULL){ //linkedList is empty therefore temp is both head and tail now
head=temp;
tail=temp;
}
else{
tail->p=temp;
tail=temp;
}
}
此外,您的班级LinkedList
不遵循The Rule of Three,因此在复制对象时会复制指针,这可能会导致麻烦。当你更多地开发你的程序时要小心。
还有一点是你main()
只能做节点插入和打印之一,所以你不能LinkedList
在添加节点的情况下打印。您可能需要这样的循环:
int main(){
LinkedList l;
cout<<"Welcome to Linkedlist creation\n";
int choice;
for(;;){
cout<<"To add a node press 1,\nTo view your list press 2\n";
if(!(cin>>choice))break; // exit when reading failed
switch(choice){
case 1:
int data;
cout<<"Enter the data to be added: ";
cin>>data;
l.addnode(data);
break;
case 2:
l.show();
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句