linked list

hello.. i take a data structure class and our teacher gave us an assignment about single linked lists

am supposed to write a getSize , deleteAt, insertAt functions

so this is what i have:
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
82
83
84
85
86
87
88
89
90
91
92
93
void  LList::insertAt(int position,string value)	//inserts a new value at the specified position.
{
	int count=0;
	Node* newN=new Node;
	newN->setInfo(value);
	if(first==0)
	{
		first=newN;
		first->setLink(0);
	}
	else
	{
		if(position<=0)
		{
			newN->setLink(first);
			first=newN;
		}
		if (position>=getSize())
		{
			Node*temp=first;
			while(temp->getLink()!=0)
				temp=temp->getLink();
			temp->setLink(newN);
			newN->setLink(0);
		}
		else
		{
			Node*temp=first;
			Node*trail=temp;
			while(temp->getLink()!=0&&count<position)
			{
				trail=temp;
				temp=temp->getLink();
				++count;
			}
			trail->setLink(newN);
			newN->setLink(temp);
		}
	}
}
void  LList::deleteAt(int pos)	//deletes the value at the specified position.
{

	if (first!=0)
	{
		if(first->getLink()!=0)
		{
			if(pos<=0)
			{
				Node*temp=first;
				first=first->getLink();
				delete temp;
			}
			else
			{
				int count=0;
				Node* temp=first;
				Node*trail=temp;
				while(count<pos&&temp!=0)
				{
					trail=temp;
					++count;
					temp=temp->getLink();
				}
				if(temp!=0)
				trail->setLink(temp->getLink());
				else
					trail->setLink(0);
				
				delete temp;
			}
		}
		else
			delete first;
	}

}

int	LList::getSize()	//returns size of the list.
{

	int count=0;
	if(first!=0)
	{
		Node*temp=first;
		while(temp!=0)
		{
			temp=temp->getLink();
			++count;
		}
	}
	return count;
}


it runs but stops working when i use deleteAt and getSize if there was only one node in the list
and i just cant figure out why!!!!
so can anyone please explain to me why that's happening????
i would really appreciate any help i can get ^_^
the problem is that you don't set first to 0 when it's deleted. In that case first points to an invalid object
I agree with the code777's answer. I'm tired, so I'll will take a look at this soon...
Last edited on
@Jackson Marie
Nope, that's not true. getSize() works correctly. [The if on line 83 could be omitted]
thank you so much it works well now!!! :D :D
Topic archived. No new replies allowed.