first time using this site and beginner in C++. I have a linked list built and am trying to convert it to a circular linked list but it's not going so well. Anyone will to give me their 2 cents as to where I am going wrong? Thanks.
Edit: The problem is, after my attempt to connect the last node to the first, I display the list again and the first node seems to have been replaced with the last node.
list before: 123456 list after: 623456
#include <iostream>
#include "SuitorNode.h"
using namespace std;
void getNumSuitors(int& numberOfSuitors);
void headInsert(SuitorNodePtr& head, int value);
int main()
{
SuitorNodePtr head, temp, remove;
int numberOfSuitors;
getNumSuitors(numberOfSuitors);
head = new SuitorNode(numberOfSuitors);
//Creates list of nodeswith the desired number of suitors
for (int i = numberOfSuitors-1; i > 0; --i)
{
headInsert(head, i);
}
// Iterate through the list and display each value
temp = head;
while (temp != NULL)
{
cout << temp->getNum();
temp = temp->getNext();
}
cout << endl;
//get to last node, connect to first, delete head
temp = head;
while (temp->getNext() != NULL)
{
temp = temp->getNext();
}
//Attempt to create circular list
temp->setNext(head->getNext());
delete head;
for (int i = 0; i < numberOfSuitors; ++i)
{
cout << temp->getNum();
temp = temp->getNext();
}
cout << endl;
return 0;
}
void getNumSuitors(int& numberOfSuitors)
{
cout << "Please enter the number of suitors:";
cin >> numberOfSuitors;
do
{
if (numberOfSuitors <= 0)
{
cout << "Invalid number of suitors. Requires more than 1 suitor\n";
cout << "Please enter the number of suitors:";
cin >> numberOfSuitors;
}
else if (numberOfSuitors == 1)
{
cout << "Trivial number of suitors. Requires more than 1 suitor\n";
cout << "Please enter the number of suitors:";
cin >> numberOfSuitors;
}
else
{
cout << "You entered " << numberOfSuitors << " suitors.\n";
}
} while (numberOfSuitors <= 1);
}
void headInsert(SuitorNodePtr& head, int value)
{
SuitorNodePtr tempPtr;
tempPtr = new SuitorNode(value);
tempPtr->setNext(head);
head = tempPtr;
}
class SuitorNode
{
public:
SuitorNode();
~SuitorNode();
SuitorNode(int initialnum);
int getNum();
SuitorNode* getNext();
void setNext(SuitorNode *nextNode);
private:
SuitorNode *next;
int num;
};
typedef SuitorNode* SuitorNodePtr;
SuitorNode::SuitorNode() : num(0), next(NULL)
{
//deliberately empty
}
SuitorNode::~SuitorNode()
{
}
SuitorNode::SuitorNode(int initialnum) : num(initialnum), next(NULL)
{
//deliberately empty
}
int SuitorNode::getNum()
{
return num;
}
SuitorNode* SuitorNode::getNext()
{
return next;
}
void SuitorNode::setNext(SuitorNode *nextNode)
{
next = nextNode;
}
You find the last node, but then set the last node nextPtr to the head node's nextPtr, instead of setting it to the head node itself.
I'm not sure you want to be deleting the head node, btw.