How to calculate the length of the linked list using constant time (O(1))

I have a function to calculate the length of the list. But this is in linear time. How could I convert this to constant time (O(1))

1
2
3
4
5
struct Node
{
    T data;
    Node *next;
};


with
1
2
Node *front;
 Node *back;


This is function to calculate the length of the linked list

1
2
3
4
5
6
7
8
9
10
11
12
13
int length() const
{
    Node *p = front;
    int n = 0;

    while (p != nullptr)
    {
        n++;
        p = p->next;
    }

    return n;
}
Last edited on
How could I convert this to constant time (O(1))
You can't. You have to maintain the length as a separate variable.
if your underlying list storage used a vector instead of pointers, you could extract it from that as well. there are pros and cons to such a simulated list, so this isn't always worth doing.
@kbw, But, I was asked to make modifications to the above function to make that to constant time.
With your current Node structure it is entirely possible to make calculating the length a constant time operation, at the cost of increased complexity for insertion and delete.

A better choice would be to maintain a specific Head object that keeps the length of the list as a member variable, in addition to the first Node pointer. Then when you pass the Head object around (which I would actually name “List”), you can get the length.

1
2
3
4
5
6
7
8
9
10
11
12
13
template <typename T>
struct Node
{
  T     data;
  Node* next;
};

template <typename T>
struct List
{
  int   size;
  Node* head;
};

Now whenever you insert or delete nodes, you must also adjust the size in the head object.

BTW, there is no point in maintaining a Node* back for a singly-linked list. (See ne555’s comment following)

Hope this helps.
Last edited on
> BTW, there is no point in maintaining a Node* back for a singly-linked list.
push_back() in O(1)
Oh, duh. Thanks. Fixed.
Topic archived. No new replies allowed.