I've just started learning linked lists and I'm having trouble with this code:
#include <iostream>
#include <conio.h>
using namespace std;
struct link{
int data;
link *next;
};
class List{
public: link *first;
List();
void add(int d);
void del(int v);
void show();
List(){
first=NULL;
}
void add(int d){
public:int *ptr, *temp;
if(first==NULL){
first = new link;
first->data=d;
first->next=NULL;
}
else{
ptr=first;
while(ptr->next!=NULL){
ptr=ptr->next;
temp=new link;
temp->data=d;
temp->next=NULL;
ptr->next=temp;
}}
}
void del(int v){
link *temp;
temp=first;
if(temp->data==v){
first=temp->next;
delete temp;
cout<<v<<" has been deleted."<<endl;
}
}
void show(){
link *temp;
temp = first;
cout<<"The list is as follows :";
while(temp!=NULL){
cout<<temp->data<<" ";
temp=temp->next;
}
}
};
int main(){
List obj;
obj.add(10);
obj.add(25);
obj.add(65);
obj.show();
cout<<endl;
obj.del(25);
obj.show();
return 0;
}
the error I'm getting :
In member function 'void List::add(int)':
[Error] expected primary-expression before 'public'
[Error] 'ptr' was not declared in this scope
[Error] 'temp' was not declared in this scope
#include <iostream>
#include <conio.h>
usingnamespace std;
struct link
{
int data;
link *next;
};
class List
{
public:
link *first;
void add(int d);
void del(int v);
void show();
List()
{
first=NULL;
}
};
void List::del(int v)
{
link *temp;
temp=first;
if(temp->data==v)
{
first=temp->next;
delete temp;
cout<<v<<" has been deleted."<<endl;
}
}
void List::show()
{
link *temp;
temp = first;
cout<<"The list is as follows :";
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
}
}
void List::add(int d)
{
link *ptr, *temp;
if(first==NULL){
first = new link;
first->data=d;
first->next=NULL;
}
else
{
ptr=first;
while(ptr->next!=NULL)
{
ptr=ptr->next;
temp=new link;
temp->data=d;
temp->next=NULL;
ptr->next=temp;
}
}
}
int main()
{
List obj;
obj.add(10);
obj.add(25);
obj.add(65);
obj.show();
cout<<endl;
obj.del(25);
obj.show();
return 0;
}
You can't declare a function 2 times in your class, but you can declare them beyond like this.
Did you mean list *ptr, *temp; ?
I have just fixed your compiler errors, look at this code then yours to see the difference.