I have a problem in the book (not for homework) that says.

List Reverse
Modify the linked list class you created in the previous programming challenges by
adding a member function named reverse that rearranges the nodes in the list so that
their order is reversed. Demonstrate the function in a simple driver program.

I am way over my head on this one. Can someone suggest how i can start? For instance what kind of loops should i use and such. This is my header file...

#ifndef NUMBERLIST_H
#define NUMBERLIST_H
#include <iostream>
using namespace std;

class NumberList
{
private:
	struct ListNode
	{
		int value;
		struct ListNode *next;
	};

	ListNode *head;
public:
	NumberList()
	{ head = NULL; }
	NumberList(NumberList &);
	//~NumberList();
	
	void appendNode(int);
	void insertNodeSmallToLarge(int);
	void insertNodeLargeToSmall(int);
	void deleteNode(int);
	int getNodeValue(int);
	int getListSize();
	void reverseNodes();
	void displayList();
};
#endif

trick is, don't move elements change points. Loop through from the start, store the first address, store the address that the next element points to then map it to point to the the first. hope that makes sense.

Chris

are you saying make an array of temporary ints, store them as you loop through the entire list, then go backwards and plug them in erasing over the old values?

I'm saying, change where the points in each ListNode points to.

start = head;
temp = start;
start = start->next;
temp->next = NULL;
temp2 = start->next;
start->next = temp;
temp = start;
start = temp2;

Something like that, I'm sure it can be done neater...and of course you want to loop it. But I'm tired and it should give you the right idea :)

Chris

This article has been dead for over six months. Start a new discussion instead.