Calculating time complexity

I am supposed to rotate a singly linked list.

0->1->2->3
k = 2
2->3->0->1

I calculated the time complexity of O(n+(n-k)) is this correct?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
template <class T>
void LinkedBag<T>::rotate(int k)
{
	Node<T>* position = getNodeAt(k); //returns the node at kth position
	Node<T>* new_node_ptr = position;
	Node<T>* first = head_ptr;
	Node<T>* new_first_ptr = new_node_ptr;
	
	while(new_node_ptr->getNext() != nullptr) //last node
	{
		new_node_ptr = new_node_ptr->getNext();
	}
	
	while(first != position)// copy all nodes upto the before of Kth node
	{
		new_node_ptr->setNext(first);
		new_node_ptr = new_node_ptr->getNext();
		first = first->getNext();
	}
	new_node_ptr->setNext(nullptr);
	head_ptr = new_first_ptr;//set head_ptr to the new modified node
}//end of rotate 
Last edited on
no.
k is a constant. It could be about N, or it could be 1 or 2.
doesn't matter … lets talk worst case of K = N-1.
now you have N+N+(N-1) which is just about 3N. but big-O ignores constants.
its O(n).

also, your algorithm is probably not optimal. You can probably write it in N iterations with some creativity. You need to find 2 things. you can search for them both in one loop through it. after finding them, you can break the pointers and assemble it in 2 chunks.
Topic archived. No new replies allowed.