Reputation: 23
I am writing a reverse function for my linked list, but I can't figure out how to point head to the new first number in the list. Declaring the head a ListNode* in main and passing it by reference will not work because I have a bunch of other functions I do not want to modify. Is there any other way of doing this? Here is my header file:
// Specification file for the NumberList class
#ifndef NUMBERLIST_H
#define NUMBERLIST_H
class NumberList
{
private:
// Declare a structure for the list
struct ListNode
{
double value; // The value in this node
struct ListNode *next; // To point to the next node
};
ListNode *head; // List head pointer
public:
// Constructor
NumberList()
{ head = nullptr; }
// Destructor
~NumberList();
// Linked list operations
void appendNode(double);
void insertNode(double);
void deleteNode(double);
int searchList(double);
void reverseList() const;
void displayList() const;
};
#endif
Here is the reverse function. Putting head = previousNode will not work:
void NumberList::reverseList() const
{
ListNode *currentNode; // points to current node
ListNode *previousNode = nullptr; // stores address of previous node
ListNode *nextNode = nullptr; // stores the address of next node
ListNode *tempNode = nullptr; //
currentNode = head;
while (currentNode != nullptr)
{
cout << "current value: " << currentNode->value << endl;
nextNode = currentNode->next;
currentNode->next = previousNode;
previousNode = currentNode;
currentNode = nextNode;
}
//head = previousNode;
}
*edit: added in main()
#include <iostream>
#include <fstream>
using namespace std;
#include "NumberList.h"
int main()
{
NumberList nList;
ifstream inFile;
double number;
double searchedNum;
inFile.open("input.txt");
if (!inFile)
{
cout << "File could not be opened!" << endl;
}
else
{
while (inFile >> number)
{
nList.appendNode(number);
}
cout << "The list after file reading:" << endl;
nList.displayList();
cout << "What number would you like to search for? ";
cin >> searchedNum;
cout << "Position: " << nList.searchList(searchedNum) << endl;
cout << "The list after reversing:" << endl;
nList.reverseList();
nList.displayList();
}
return 0;
}
Upvotes: 0
Views: 196
Reputation: 4845
Here's an iterative version (I marked changes with // Added *
):
void NumberList::reverseList()
{
ListNode *currentNode; // points to current node
ListNode *previousNode = nullptr; // stores address of previous node
ListNode *nextNode = nullptr; // stores the address of next node
currentNode = head;
ListNode* temp; // Added*
while (currentNode != nullptr)
{
temp = currentNode->next; // Added *
nextNode = currentNode->next;
currentNode->next = previousNode;
previousNode = currentNode;
currentNode = temp; // Added *
}
}
Upvotes: 1
Reputation: 40859
ListNode * reverse_list(ListNode * list, ListNode * new_head = nullptr)
{
if (list == nullptr) return new_head;
ListNode * tmp = list->next;
list->next = new_head;
return reverse_list(tmp, list);
}
head = reverse_list(head);
Upvotes: 0