Following is my code to reverse a linked list:
public LinkedList reverse() {
LinkedList m = new LinkedList();
Node temp = this.getHeadNode();
while(temp!= null) {
m.insertFirst(temp.getElement());
temp = temp.getNext();
}
m.getTailNode().setNext(null);
return m;
}
For the local variable LinkedList m i declared in my function, does that mean i am using O(n) amount of additional space or is it considered constant amount of space?
since you’re creating new instance of linked list – you will have 2 copies of list in memory. The list will contain references to objects, so if you want to count instances of objects – then you are safe and amount of additional memory is O(1). But list itself takes some memory, so if you count number of “cells” in lists – then yes, you have O(N) additional memory being used.