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

时间:2015-10-19 01:24:01

标签: c++ overloading singly-linked-list

我无法弄清楚如何将我的单链表放入我的排序方法中。我应该重载下标,以便能够访问我的列表的不同部分。我遇到的问题是弄清楚如何通过sort函数修改这个列表。

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");

}

1 个答案:

答案 0 :(得分:0)

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;

        }

        }

    }
相关问题