Where is the mistake ?

Posted by mr.bio on Stack Overflow See other posts from Stack Overflow or by mr.bio
Published on 2010-06-03T09:33:18Z Indexed on 2010/06/03 9:34 UTC
Read the original article Hit count: 334

Filed under:
|

Hi ...

i am implementing a simple linked list in c++. I have a mistake and i don't see it :(

#include <stdexcept>
#include <iostream>

struct Node {

    Node(Node *next, int value):
    next(next), value(value) {
    }
    Node *next;
    int value;
};

class List {
    Node *first; // Erstes Element , 0 falls die Liste leer ist
    int len; // Laenge der liste
    Node *nthNode(int index); // Hilfsfunktion : O( index )

public:
    // Default - Konstruktor ( Laenge 0): O (1)

    List():first(0),len(0){
    }
    // Copy - Konstruktor : O(other.len)
    List(const List & other){

    };

    // Zuweisungs - Operator O(len +other.len)
    List &operator=(const List &other) {
        clear();
        if(!other.len) return *this;
        Node *it = first = new Node(0,other.first->value);
        for (Node *n = other.first->next; n; n = n->next) {
            it = it->next = new Node(0, n->value);
        }
        len = other.len;
        return *this;
    }

    // Destruktor ( gibt den Speicher von allen Nodes frei ): O( len )
    ~List(){

    };
    // Haengt der Liste ein Element hinten an: O( len )
    void push_back(int value){

    };
    // Fuegt am Anfang der Liste ein Element ein : O (1)
    void push_front(int value){
        Node* front = new Node(0,value);

        if(first){
            first  = front;
            front->next = 0;
        }else{
            front->next = first;
            first = front;

        }
        len++;
    };

    // gibt eine Referenz auf das index -te Element zurueck : O( index )
    int &at(int index){
        int count = 0 ;
        int ret ;
        Node *it = first;
        for (Node *n = first->next; n; n = n->next) {
            if(count==index) ret = n->value;
            count++;
        }
        return ret ;
    };

    // Entfernt alle Elemente : O(len)
    void clear(){


    };

    // Zeigt alle Elemente an: hier : O( len * len )
    void show() {
        std::cout << " List [" << len << " ]:{ ";
        for (int i = 0; i < len; ++i) {
            std::cout << at(i) << (i == len - 1 ? '}' : ',');
        }
        std::cout << std::endl;
    }
};

/*
 * 
 */
int main() {

    List l;
 //   l. push_back(1);
 //   l. push_back(2);
    l. push_front(7);
    l. push_front(8);
    l. push_front(9);
    l.show();
   // List(l). show();
}

it works ... but the output is :

List [3 ]:{ 0,134520896,9484585}

© Stack Overflow or respective owner

Related posts about c++

Related posts about linked-list