- add insert for list and arraylist

pull/11/head
Emir Pasic 9 years ago
parent 888e7f29b1
commit c7abdd28b3

@ -138,6 +138,7 @@ type Interface interface {
Contains(elements ...interface{}) bool
Sort(comparator utils.Comparator)
Swap(index1, index2 int)
Insert(index int, elements ...interface{})
containers.Interface
// Empty() bool
@ -180,6 +181,8 @@ func main() {
_ = list.Size() // 0
list.Add("a") // ["a"]
list.Clear() // []
list.Insert(0, "b") // ["b"]
list.Insert(0, "a") // ["a","b"]
}
```

@ -149,6 +149,32 @@ func (list *List) Swap(i, j int) {
}
}
// Inserts values at specified index position shifting the value at that position (if any) and any subsequent elements to the right.
// Does not do anything if position is negative or bigger than list's size
// Note: position equal to list's size is valid, i.e. append.
func (list *List) Insert(index int, elements ...interface{}) {
if !list.withinRange(index) {
// Append
if index == list.size {
list.Add(elements...)
}
return
}
l := len(elements)
list.growBy(l)
list.size += l
// Shift old to right
for i := list.size - 1; i >= index+l; i-- {
list.elements[i] = list.elements[i-l]
}
// Insert new
for i, element := range elements {
list.elements[index+i] = element
}
}
func (list *List) String() string {
str := "ArrayList\n"
values := []string{}
@ -161,7 +187,7 @@ func (list *List) String() string {
// Check that the index is withing bounds of the list
func (list *List) withinRange(index int) bool {
return index >= 0 && index < list.size && list.size != 0
return index >= 0 && index < list.size
}
func (list *List) resize(cap int) {

@ -27,6 +27,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package arraylist
import (
"fmt"
"github.com/emirpasic/gods/utils"
"testing"
)
@ -120,6 +121,19 @@ func TestArrayList(t *testing.T) {
t.Errorf("Got %v expected %v", actualValue, true)
}
list.Insert(0, "h")
list.Insert(0, "e")
list.Insert(1, "f")
list.Insert(2, "g")
list.Insert(4, "i")
list.Insert(0, "a", "b")
list.Insert(list.Size(), "j", "k")
list.Insert(2, "c", "d")
if actualValue, expectedValue := fmt.Sprintf("%s%s%s%s%s%s%s%s%s%s%s", list.Values()...), "abcdefghijk"; actualValue != expectedValue {
t.Errorf("Got %v expected %v", actualValue, expectedValue)
}
}
func BenchmarkArrayList(b *testing.B) {

@ -30,6 +30,7 @@ type Interface interface {
Contains(elements ...interface{}) bool
Sort(comparator utils.Comparator)
Swap(index1, index2 int)
Insert(index int, elements ...interface{})
containers.Interface
// Empty() bool

Loading…
Cancel
Save