From e709a4b5ea88c8f3f566c8c8cea95a3e529d52a4 Mon Sep 17 00:00:00 2001 From: Mahadev Date: Tue, 26 Dec 2017 19:19:18 +0530 Subject: [PATCH] Add IndexOf method to SinglyLinkedList --- lists/singlylinkedlist/singlylinkedlist.go | 12 +++++++++ .../singlylinkedlist/singlylinkedlist_test.go | 27 +++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/lists/singlylinkedlist/singlylinkedlist.go b/lists/singlylinkedlist/singlylinkedlist.go index 139925b..3182af3 100644 --- a/lists/singlylinkedlist/singlylinkedlist.go +++ b/lists/singlylinkedlist/singlylinkedlist.go @@ -154,6 +154,18 @@ func (list *List) Values() []interface{} { return values } +//IndexOf returns index of provided element +func (list *List) IndexOf(value interface{}) int{ + if list.size == 0 { + return -1 + } + for index, element := range list.Values() { + if element == value { + return index + } + } + return -1 +} // Empty returns true if list does not contain any elements. func (list *List) Empty() bool { return list.size == 0 diff --git a/lists/singlylinkedlist/singlylinkedlist_test.go b/lists/singlylinkedlist/singlylinkedlist_test.go index 27daacc..0bebbb3 100644 --- a/lists/singlylinkedlist/singlylinkedlist_test.go +++ b/lists/singlylinkedlist/singlylinkedlist_test.go @@ -133,6 +133,33 @@ func TestListValues(t *testing.T) { } } +func TestListIndexOf(t *testing.T) { + list := New() + + expectedIndex := -1 + if index := list.IndexOf("a"); index != expectedIndex{ + t.Errorf("Got %v expected %v",index,expectedIndex) + } + + list.Add("a") + list.Add("b", "c") + + expectedIndex = 0 + if index := list.IndexOf("a"); index != expectedIndex{ + t.Errorf("Got %v expected %v",index,expectedIndex) + } + + expectedIndex = 1 + if index := list.IndexOf("b"); index != expectedIndex{ + t.Errorf("Got %v expected %v",index,expectedIndex) + } + + expectedIndex = 2 + if index := list.IndexOf("c"); index != expectedIndex{ + t.Errorf("Got %v expected %v",index,expectedIndex) + } +} + func TestListInsert(t *testing.T) { list := New() list.Insert(0, "b", "c")