简体   繁体   中英

How to change my Linked-List insert function from O(N) to O(1)

I implemented my linkedList function which inserts at the end, but I used the brute force method going through until the end and then adding it. I would like to change it to O(1). If you guys have any tips that would be great.

The only way to make this O(1) is to maintain a reference to the last Object in your List object. Whenever a new object is inserted at the end of the List , the pointer is updated to point to it.

Your actual problem has already been answered: Store an additional tail pointer at which you can insert without looping over the entire list.

But also take a look at your code:

for (node; node->getNext() != NULL && node->getNext()->getElement() != data;)
     node= node->getNext();
node->setNext(insertNode);

The second condition in the for loop looks kind of weird to me. In case you would want to append a new element with element == data, your loop would stop at any existing element with that value and you would attach your newly allocated element just before it ... and lose all old elements starting with the existing node with element == data. Looks like a bug go me.

As other people have said, you need to add a tail node to your list, and then you can use this implementation for insertAtEnd() :

template <class Object>
void List<Object>::insertAtEnd(const Object& o)
{       
    ListNode<Object>* insertNode = new ListNode<Object>(o, nullptr);
    if (!head) head = insertNode;
    if (tail) tail->setNext(insertNode);
    tail = insertNode; 
}

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