将链表转换为循环列表

时间:2015-06-20 00:51:05

标签: singly-linked-list

首次在C ++中使用此站点和初学者。我有一个链表建立,我试图将其转换为循环链表,但它不是那么顺利。任何人都会给我2美分我错的地方?谢谢。

编辑:问题是,在我尝试将最后一个节点连接到第一个节点后,我再次显示列表,第一个节点似乎已被最后一个节点替换。

之前的列表:123456 列出: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;
}

1 个答案:

答案 0 :(得分:0)

找到最后一个节点,但是将最后一个节点nextPtr设置为头节点的nextPtr,而不是将其设置为头节点本身。

我不确定你是否想要删除头节点,顺便说一句。