Is DoubleLinkedList method inefficient?
I wrote a method myself to add it to the back
public void addBack(int data){ Node n = new Node(data); if(rear == null){ rear = n; front = n; return; } if( front.next == null){ front.next = n; n.before = front; rear = n; } n.before = rear; rear = n; rear.before.next = rear; }
And this is the pattern function. What are the disadvantages of mine? Or where are there errors? I've tested it, and everything seems to work when inserted once, or even when inserted multiple times.
public void addAtEnd(int dataValue){ if (front == null){ addFront(dataValue); return; } Node lastNode = front; while (lastNode != null){ if (lastNode.next == null){ Node newNode = new Node(dataValue); newNode.next = null; newNode.before = lastNode; lastNode.next = newNode; lastNode.next = newNode; rear = newNode; return; } lastNode = lastNode.next; } }
The second variant looks like a typical implementation for Single Linked without Tailpointer.
Because then you have to iterate about the list.
So my own is better?
However, there are some potential problems and inefficient aspects in your implementation:
Here is a revised approach that addresses the problems mentioned and provides a more efficient implementation:
In this revised version will be
used as a pointer to the last item of the list. If the new item is added, it will be added directly to
hung, thereby avoiding the loop for searching for the last element. This will make the addition at the end of the list more efficient regardless of the length of the list.
So mine would be the above that with the loop is the sample solution