| 1 | /** |
| 2 | * |
| 3 | */ |
| 4 | package net.digitaltsunami.word.trie; |
| 5 | |
| 6 | /** |
| 7 | * @author dhagberg |
| 8 | * |
| 9 | */ |
| 10 | public class LexLinkedCharTrieNode extends LinkedCharTrieNode { |
| 11 | |
| 12 | protected LexLinkedCharTrieNode(CharTrieNode parent, char value) { |
| 13 | super(parent, value); |
| 14 | // TODO Auto-generated constructor stub |
| 15 | } |
| 16 | |
| 17 | /** |
| 18 | * @param value |
| 19 | */ |
| 20 | public LexLinkedCharTrieNode(char value) { |
| 21 | super(value); |
| 22 | } |
| 23 | |
| 24 | /** |
| 25 | * @param rootNode |
| 26 | */ |
| 27 | public LexLinkedCharTrieNode(boolean rootNode) { |
| 28 | super(rootNode); |
| 29 | } |
| 30 | |
| 31 | @Override |
| 32 | public CharTrieNode getChild(char value) { |
| 33 | LinkedCharTrieNode sibling = getFirstChild(); |
| 34 | while (sibling != null) { |
| 35 | if (value > sibling.getValue()) { |
| 36 | // Value > child, still could be found |
| 37 | sibling = sibling.getNextSibling(); |
| 38 | } else if (value == sibling.getValue()) { |
| 39 | // Value == child, return |
| 40 | return sibling; |
| 41 | } else { |
| 42 | // Value < child, can't be found as they are in order |
| 43 | return null; |
| 44 | } |
| 45 | } |
| 46 | return null; |
| 47 | } |
| 48 | |
| 49 | @Override |
| 50 | public CharTrieNode addChild(char value) { |
| 51 | LinkedCharTrieNode sibling = getFirstChild(); |
| 52 | while (sibling != null) { |
| 53 | // if value > sibling |
| 54 | if (value > sibling.getValue()) { |
| 55 | if (sibling.getNextSibling() != null) { |
| 56 | // New value still less than remaining siblings, |
| 57 | // continue searching. |
| 58 | sibling = sibling.getNextSibling(); |
| 59 | } else { |
| 60 | // Reached the end of the sibling list. Add new node and |
| 61 | // append to the last node in the list. |
| 62 | LinkedCharTrieNode newNode = new LexLinkedCharTrieNode(this, value); |
| 63 | sibling.appendNode(newNode); |
| 64 | /* |
| 65 | * sibling.setNextSibling(newNode); |
| 66 | * newNode.setPriorSibling(sibling); |
| 67 | */ |
| 68 | return newNode; |
| 69 | } |
| 70 | } else if (value == sibling.getValue()) { |
| 71 | // Value == sibling, already exists, just return |
| 72 | return sibling; |
| 73 | } else { |
| 74 | // Value < sibling, list is in order, so it won't be found. |
| 75 | // Create new, insert it, and return the new node. |
| 76 | LinkedCharTrieNode newNode = new LexLinkedCharTrieNode(this, value); |
| 77 | sibling.prependNode(newNode); |
| 78 | return newNode; |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | // First child node to be added, add and return. |
| 83 | LinkedCharTrieNode newNode = new LexLinkedCharTrieNode(this, value); |
| 84 | setFirstChild(newNode); |
| 85 | return newNode; |
| 86 | } |
| 87 | |
| 88 | } |