reversing a linked list (nodes) random crash

I'm trying to write a function to print out the values of a linked list's nodes in reverse, it works perfectly fine, but causes my program to crash once it finishes and I can't seem to figure out why.

function code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void List::reverse(ListNode *head) const{

    ListNode* newList = NULL;
	ListNode* cur = head;
	ListNode* next = NULL;

	while (cur != NULL)
	{
		next = cur->next;
		cur->next = newList;
		newList = cur;
		cur = next;
	}
        for (int i = 0; i < getLength(); i++){
            cout << newList->item << " ";
            newList = newList->next;
        }
}


and in my main function this is how i'm calling it

aList.reverse(aList.find(1));

my list contains 12 1 2 3 4

reverse prints out 4 3 2 1 12
then my program crashes.

I'm guessing this is what is causing the crash, but I'm not sure. is there another way to call this function when head is private? Thanks guys
Last edited on
nickcplusplus wrote:
1
2
3
4
5
6
7
while (cur != NULL)
	{
		next = cur->next;
		cur->next = newList;
		newList = cur;
		cur = next;
	}


You check to make sure cur actually points to something. But you don't check to see if cur->next points to something. The last node next will be NULL and you're accessing something that doesn't exist.

nickcplusplus wrote:
I'm guessing this is what is causing the crash, but I'm not sure. is there another way to call this function when head is private?

I'm not 100% sure what you're referring to. Head as in the member of the list that points to the first node? or head as in the one that you're passing?
Last edited on
it still crashes if I use while (cur-> next!= NULL)
Topic archived. No new replies allowed.