C链表实现的麻烦

问题描述 投票:0回答:1

我曾期望在C ++中为一个任务创建一个链表,但是我在使用一种特定方法时遇到了很多麻烦。

#include "myLList.h"
#include "Datum.h"
#include <stddef.h>

myLList::myLList()
{
    head = curr = tail = NULL;
}

myLList::myLList(float arr[])
{
    if(arr[0] = NULL);
        exit(0);
    int arrayLength = sizeof(arr)/sizeof(arr[0]);

    Datum *temp = new Datum(arr[0]);
    head = temp;
    tail = temp;

    for(int i = 1; i < arrayLength; i++)
    {
        insertAtEnd(arr[i]);
    }

}

void myLList::insertAtEnd(float value)
{
    Datum *temp = new Datum(value);
    if(head == NULL)
    {
        head = temp;
        tail = head;
        temp = NULL;
    }
    else
    {
        tail->setNext(*temp);
        tail = temp;
    }
}

Datum myLList::operator[](int index)
{
    Datum *temp = head;
    for(int i = 0; i++; i < index)
    {
        temp = temp->getNext();
    }
    return temp->getData();
}


void myLList::insert(int index, float value)
{
    Datum *temp = new Datum(value);
    curr = head;
    Datum *prev = curr;

    for(int i = 1; i < index; i++)
    {
        prev = curr;
        curr = curr->getNext();
    }

    prev->setNext(*temp);
    temp->setNext(*curr);
}


myLList::~myLList()
{
    //dtor
}

使用以下main.cpp测试insertAtEnd和重载[]方法时:

#include <iostream>
#include "Datum.h"
#include "myLList.h"
#include <stddef.h>


using namespace std;

int main()
{
 myLList linkedList = myLList();

    linkedList.insertAtEnd(1);
    linkedList.insertAtEnd(2);
    linkedList.insertAtEnd(3);

    cout << "third element: " << linkedList[2].getData() << endl;
}

无论我将什么索引压入重载的[]运算符中,输出都只是链表顶部的值。任何帮助将不胜感激

c++ linked-list operator-overloading singly-linked-list
1个回答
2
投票

在函数内部重载[]运算符:

更改此:

© www.soinside.com 2019 - 2024. All rights reserved.