Singly Linked List error

Hi Guyz.. Im a beginner in C++ and I am having a bit of trouble with this code which is a HW...
The purpose of this program is to read words from a file, store these words in a singly linked list then sort them and re-type them on the same file..

The problem with my code is that it just crashes and exits when it perform the sorting function
This is a member function of the class Link

I really think there is something wrong with Line 4 :)

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
void LinkSelSort()//added this function to sort elements of a linked list
		{
			Node *p=Root;
			Node *r= Root->getNext();
			Node T;

			while (p->getNext()){
				while(r)
				{
					if (strcmp(p->getString(),r->getString())>0)
					{
						strcpy(T.getString(),p->getString());
						strcpy(p->getString(),r->getString());
						strcpy(r->getString(),T.getString());
					}
					r=r->getNext();
				}
				p=p->getNext();
			}

			if (strcmp(p->getString(),r->getString())>0){// last cell comparison
				        strcpy(T.getString(),p->getString());
						strcpy(p->getString(),r->getString());
						strcpy(r->getString(),T.getString());
			}
		
		}//end Of LinkSort 


Thank you in advance
1
2
3
4
5
6
7
8
9
10
11
12
while (p->getNext()){
	while(r)
	{
	//...
	}
	//Here `r' is NULL
	p=p->getNext();
}
//Here `p' is the last cell (it has no `next')


if (strcmp(p->getString(),r->getString())>0){//dereferencing a NULL pointer 
_ The inner loop will only execute one time, you need to reset `r'
_ You are making too much swaps for a selection sort (also, call a `swap' function)
_ As you've got a list, consider doing `merge sort'
Thank you alot... I've just edited it.. the r was really pointing to NULL and I was doing a very selly mistake

1
2
3
4
						strcpy(T.getString(),p->getString());
						strcpy(p->getString(),r->getString());
						strcpy(r->getString(),T.getString());
					


it should be like this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
while (p->getNext()){
				while(r)
				{
					if (strcmp(p->getString(),r->getString())>0)
					{
						
						T.setstring(p->getString());
						p->setstring(r->getString());
						r->setstring(T.getString());
						
					}
					r=r->getNext();
				}
				p=p->getNext();
				r=p;
			}
Topic archived. No new replies allowed.