In my implementation of a linked list, there are two methods. When I call one method, it affects the results of the other method. One method is concatenateLL()
to concatenate two list and one method is getNumberOfNodes()
which returns number of nodes in linked list. For my method concatenate, I am supposed to return a new list which is a concatenation of two lists. But in my code, the resulting new list affect the list in the first parameter. Lets say I pass list l
and m
and parameters and I return a new list.
The problem is that the new is just list l
which now includes elements of list m
(due to concatenation). And because of this, when I call getNumberOfNodes()
on list l
and m
, I get the wrong value.
Here is my code:
public static LinkedList concatenateLL(LinkedList l, LinkedList m) {
LinkedList a = l;
Node l_last = a.getTailNode();
Node m_first = m.getHeadNode();
l_last.setNext(m_first);
a.tail = m.getTailNode();
return a;
}
public int getNumberOfNodes(Node h) {
if(h == null)
return 0;
return 1 + getNumberOfNodes(h.getNext());
}
public static void print(LinkedList l) {
Node v = l.getHeadNode();
while(v != null) {
System.out.print(v.getElement()+" ");
v = v.getNext();
}
System.out.println();
}
public static void main(String[] args) throws IndexOutOfBoundsException {
// TODO Auto-generated method stub
LinkedList l = new LinkedList();
LinkedList m = new LinkedList();
l.insertFirst(5);
l.insertFirst(7);
l.insertFirst(3);
l.insertFirst(6);
print(l);
m.insertFirst(2);
m.insertFirst(4);
m.insertFirst(9);
m.insertFirst(8);
m.insertLast(10);
m.insertLast(12);
print(m);
LinkedList n = concatenateLL(l, m);
print(n);
System.out.println(l.getNumberOfNodes(l.getHeadNode()));
System.out.println(m.getNumberOfNodes(m.getHeadNode()));
}
In the main method, length of list l
should return 4
and list m
should return 6
. But after I call concatenation method before calling getNumberOfNodes()
, I get length of l
as 10
(which is number of nodes of list n
as a result of concatenation of l
and m
) and length of m
as 15
(which I have no idea why).