From f8246956c4decce909a81bf7912c9bbe524515ed Mon Sep 17 00:00:00 2001 From: Jan Philipp Timme Date: Sat, 8 Nov 2014 18:46:54 +0100 Subject: [PATCH] Reuse free null-nodes in the list to add new entities. --- .../datastructure/ConcurrentLinkedList.java | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/de/teamteamteam/spacescooter/datastructure/ConcurrentLinkedList.java b/src/de/teamteamteam/spacescooter/datastructure/ConcurrentLinkedList.java index 68ea4d7..760b65d 100644 --- a/src/de/teamteamteam/spacescooter/datastructure/ConcurrentLinkedList.java +++ b/src/de/teamteamteam/spacescooter/datastructure/ConcurrentLinkedList.java @@ -17,6 +17,7 @@ public class ConcurrentLinkedList { */ public ConcurrentLinkedList() { this.head = new ConcurrentLinkedListNode(); + this.head.setNext(new ConcurrentLinkedListNode()); } @@ -24,10 +25,18 @@ public class ConcurrentLinkedList { * Add an element to the list. */ public void add(T element) { - ConcurrentLinkedListNode newNode = new ConcurrentLinkedListNode(element); - ConcurrentLinkedListNode currentNode = this.head; - while(currentNode.hasNext()) currentNode = currentNode.next(); - currentNode.setNext(newNode); + ConcurrentLinkedListNode currentNode = this.head.next(); + //jump to the next node until we reached the last OR we got one that has a null value. + while(currentNode.hasNext() && currentNode.getValue() != null) currentNode = currentNode.next(); + //if it has a null value, add the element here + if(currentNode.getValue() == null) { + currentNode.setValue(element); + } else { + //since getValue must be != null, we surely reached the _last_ node. + //create a new node and append it to the list. + ConcurrentLinkedListNode newNode = new ConcurrentLinkedListNode(element); + currentNode.setNext(newNode); + } } /**