简体   繁体   中英

Trivial singly-linked list inquiry

The addToHead function of the linked list class is not working properly. The function seems to be replacing the head. Help. Please.

template <class T>
class LinkedNode {
  public:
    LinkedNode(T);
    T element;
    LinkedNode<T> *next;
};

template <class T>
LinkedNode<T>::LinkedNode(T e){
    element = e;
    next = 0;
}
///////////////////////////////////////////
template <class E>
class LinkedList {
  public:
    LinkedList();
    void addToHead(E);
    LinkedNode<E> *head, *tail, *temp;
};

template <class E>
LinkedList<E>::LinkedList() {
    head = tail = NULL;
}

template <class E>
void LinkedList<E>::addToHead(E e) {
    LinkedNode<E> a(e);
    if (head == NULL)
        head = tail = &a;
    else {
        a.next = head;
        head = &a;
    }
}

int main(){
    LinkedList<int> list;
    list.addToHead(55);
    list.addToHead(22);
    cout << list.head->element << " trivial "<< list.head->next->element << endl;
}

In addToHead() , you are assigning the address of a local variable to the head element of your list. After this function returns, the local variable is destroyed and must not be accessed.

One way to fix this is to use dynamic allocation to make a new LinkedNode<E> :

template <class E>
void LinkedList<E>::addToHead(E e) {
    LinkedNode<E> *a = new LinkedNode<E>(e);
    if (head == NULL)
        head = tail = a;
    else {
        a->next = head;
        head = a;
    }
}

After allocating memory for this node, your LinkedList class should also be responsible for freeing the node (with delete ) at some point in the future.

LinkedNode a(e); is only in the scope of addToHead. The pointer to it ( &a ) gets invalidated as soon as the function returns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM