Need help: Linked List, reverse List

Feb 27, 2014 at 8:33am
I'm trying to write a reverse linked list code
The input, output is all ok.
Something is wrong in this code but it seem logical to me so can someone point the errors in here.
void reverseList( TheList *&head)
{// Pb : Point back, Pre : Previous num
TheList *Cur, *Pb, *Pre;
Cur = head ->nextNum;
Pb = head;
Pre = head;
while ( Pb != NULL)
{
Pb = Cur;
Cur = Cur->nextNum;
Pb->nextNum = Pre;
if ( Pb == NULL)
{
head->nextNum=NULL;
head = Pre;
}
Pre = Pb;
}
Output(head);
}
Thanks ^^, sr for my bad english
Last edited on Feb 27, 2014 at 9:13am
Feb 27, 2014 at 8:44am
right here...
if ( Pb = NULL)

should be...
if ( Pb == NULL)
Feb 27, 2014 at 8:48am
wow , i'm so stupid ....
Feb 27, 2014 at 8:50am
still i did some fixing, it isnt reverse...

Last edited on Feb 27, 2014 at 9:08am
Feb 27, 2014 at 9:17am
the only other thing that stands out to me is this...
1
2
Pb->nextNum = Pre;
if ( Pb == NULL)


obviously Pb can never be null, the previous line would crash.
Feb 27, 2014 at 9:21am
at the top of the line
Pb = Cur;
so when Cur = NULL => Pb =>NULL
the if statment there is for when the point reach the end of the list it will move the head point to the end after reverse
Feb 27, 2014 at 11:15am
but if that happens
Pb->nextNum = Pre;
will crash because Pb is null

also, please use code tags around code snippets. Just highlight the code and click <> icon on the right.
Last edited on Feb 27, 2014 at 11:16am
Feb 28, 2014 at 12:24am
I got it working so thank you so much
This is my code after
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void reverseList( TheList *&head)
{// Pb : Point back, Pre : Previous num
	TheList *Cur, *Pb, *Pre;
	Cur = head ->nextNum;
	Pb = head;	
	Pre = head;
	while ( Cur != NULL)
	{
		Pb = Cur;
		Cur = Cur->nextNum;
		Pb->nextNum = Pre;
		Pre = Pb;
	}
	head->nextNum = NULL;
	head = Pb;
	Output(head);
}
Topic archived. No new replies allowed.