001 package lrs.visitor; 002 003 import lrs.*; 004 import java.util.*; 005 006 /** 007 * Algorithm for inserting elements into an LRStruct in order. 008 * @author Mathias Ricken - Copyright 2008 - All rights reserved. 009 */ 010 public class InsertInOrder<T> implements IAlgo<T, LRStruct<T>, T> { 011 private Comparator<T> _order; 012 013 public InsertInOrder(Comparator<T> ord) { 014 _order = ord; 015 } 016 017 /** 018 * Simply inserts the given parameter n at the front. 019 * @param host an empty LRStruct. 020 * @param n n[0] is an Object to be inserted in order into host, 021 * based on the given Comparator. 022 * @return LRStruct<T> 023 */ 024 public LRStruct<T> emptyCase(LRStruct<T> host, T... n) { 025 return host.insertFront(n[0]); 026 } 027 028 /** 029 * Based on the comparison between first and n, 030 * inserts at the front or recurs! 031 * @param host a non-empty LRStruct. 032 * @param n n[0] is an Object to be inserted in order into host, 033 * based on the given Comparator. 034 * @return LRStruct<T> 035 */ 036 public LRStruct<T> nonEmptyCase(LRStruct<T> host, T... n) { 037 if (_order.compare(n[0], host.getFirst()) < 0) { 038 return ((LRStruct<T>)host).insertFront(n[0]); 039 } 040 else { 041 return host.getRest().execute(this, n); 042 } 043 } 044 } 045