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...

#include <iostream>
using namespace std;

class NumberList
	struct ListNode
		int value;
		struct ListNode *next;

	ListNode *head;
	{ head = NULL; }
	NumberList(NumberList &);
	void appendNode(int);
	void insertNodeSmallToLarge(int);
	void insertNodeLargeToSmall(int);
	void deleteNode(int);
	int getNodeValue(int);
	int getListSize();
	void reverseNodes();
	void displayList();

Recommended Answers

All 4 Replies

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.


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 :)


Yup that helps. Thanks alot

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.