c++ - 使用下标重载的单链表排序

标签 c++ overloading singly-linked-list

我不知道如何将我的单向链表放入我的排序方法中。我应该重载下标以便能够访问列表的不同部分。我遇到的问题是弄清楚如何通过排序功能修改此列表。

template <typename E> 
class SNode {
private:
    E elem;
    SNode<E>* next;
    friend class SLinkedList<E>;
    template <typename E>
    friend ostream& operator <<(ostream& out, SLinkedList<E>& v);
};

template <typename E> 
class SLinkedList {
 public:
    SLinkedList();
    ~SLinkedList();
    bool empty() const;
    const E& front() const;
    void addFront(const E& e);
    void removeFront();
    int getSize();
    SNode<E>* getHead();
    void sort();
    void printDetails() const;

    //overload

    E& operator[] (const int index);
    const E& operator[] (const int index) const;

private:
    SNode<E>* head;
    int size;
 };
    template <typename E>
    E& SLinkedList<E>::operator [](const int index) {
    SNode<E>* temp = head;

    for (int i = 0; i < index; i++) {
        temp = temp->next;
    }
    E out = temp->elem;
    return out;
    }

template <typename E>
const E& SLinkedList<E>::operator [](const int index) const {
    SNode<E>* temp = head;

    for (int i = 0; i < index; i++) {
        temp = temp->next;
    }    
    E out = temp->elem;
    return out;
}

template <typename E>
void SLinkedList<E>::sort() {
    for (int i = 1; i < getSize(); ++i) {
        E curr = (*this)[i];
        int j = i - 1;
        while (j >= 0 && (*this)[j] > curr); {
            E temp = (*this)[i];
            this->elem = (*this)[j];
            this[j] = temp;
            j = j - 1;
        }
        (*this)[j + 1] = curr;

    }
}

void main() {
SLinkedList<float> lst;

int lstElems = 10;
srand(time(NULL));
for (int i = 0; i < lstElems; i++) {
    lst.addFront(randGen());
}
cout << "Unsorted list: " << lst << endl;
lst.printDetails();
cout << "TEST SINGLE LIST ELEMENT: " << lst[1] << endl;
lst.sort();
cout << "Sorted list: " << lst << endl;



system("pause");

最佳答案

Reviewing your code, you seem to have an incorrect implementation of bubble sort.
The below impl is for bubble sort. (do remember there are better sorting algorithms than bubble sort, which i won't get into )
      int j = 0; 

      while (swapped) {

            swapped = false;

            j++;

        for (int i=0; i < getSize() - j; i++) {

        if ((*this)[i] > (*this)[i+1]) {

            E temp = (*this)[i];

            (*this)[i] = (*this)[i+1];

            (*this)[i+1]=temp;

            swapped = true;

        }

        }

    }

关于c++ - 使用下标重载的单链表排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33205223/

相关文章:

c++ - 在 C++ 中重载 Subscript[] 运算符以设置类(量词)的大小。

java - 如何调用带有短参数的方法?

c - 使用递归函数反向打印链表

C 编程中的代码安全(避免任何分段/错误)

c - 不明白 Valgrind 中内存泄漏显示的来源

c++ - 如何使用 boost 日志防止内存增长?

c++ - 如何在 [action-if-true] 中执行多个操作

C++编译错误: no matching constructor for initialization

javascript - 使用联合类型的 Typescript 中的重载函数的参数数量和类型不同

c++ - 在无序 map<string,vector<string>> 上使用 find() 与 C++ 中的有序 map 花费相同的时间