Just started linked lists. Need help:

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

What am I doing wrong here ?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <iostream>
#include <conio.h>
using namespace 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.
Topic archived. No new replies allowed.