diff --git a/README.md b/README.md index f87ed9c..a14d9cd 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ Implementation of various data structures in Go. - [TreeSet](#treeset) - [Lists](#lists) - [ArrayList](#arraylist) + - [SinglyLinkedList](#singlylinkedlist) - [DoublyLinkedList](#doublylinkedlist) - [Stacks](#stacks) - [LinkedListStack](#linkedliststack) @@ -183,6 +184,43 @@ func main() { } ``` +#####SinglyLinkedList + +This structure implements the _List_ interface and is a linked data structure where each element points to the next in the list. + +Direct access method _Get(index)_ and _Remove()_ are of linear performance. _Append_ and _Prepend_ are of constant time performance. Checking with _Contains()_ is of quadratic complexity. + +```go +package main + +import ( + sll "github.com/emirpasic/gods/lists/singlylinkedlist" + "github.com/emirpasic/gods/utils" +) + +func main() { + list := sll.New() + list.Add("a") // ["a"] + list.Append("b") // ["a","b"] (same as Add()) + list.Prepend("c") // ["c","a","b"] + list.Sort(utils.StringComparator) // ["a","b","c"] + _, _ = list.Get(0) // "a",true + _, _ = list.Get(100) // nil,false + _ = list.Contains("a", "b", "c") // true + _ = list.Contains("a", "b", "c", "d") // false + list.Remove(2) // ["a","b"] + list.Remove(1) // ["a"] + list.Remove(0) // [] + list.Remove(0) // [] (ignored) + _ = list.Empty() // true + _ = list.Size() // 0 + list.Add("a") // ["a"] + list.Clear() // [] +} + + +``` + #####DoublyLinkedList This structure implements the _List_ interface and is a linked data structure where each element points to the next and previous element in the list. diff --git a/examples/singlylinkedlist.go b/examples/singlylinkedlist.go new file mode 100644 index 0000000..6725236 --- /dev/null +++ b/examples/singlylinkedlist.go @@ -0,0 +1,52 @@ +/* +Copyright (c) 2015, Emir Pasic +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +package examples + +import ( + sll "github.com/emirpasic/gods/lists/singlylinkedlist" + "github.com/emirpasic/gods/utils" +) + +func SinglyLinkedListExample() { + list := sll.New() + list.Add("a") // ["a"] + list.Append("b") // ["a","b"] (same as Add()) + list.Prepend("c") // ["c","a","b"] + list.Sort(utils.StringComparator) // ["a","b","c"] + _, _ = list.Get(0) // "a",true + _, _ = list.Get(100) // nil,false + _ = list.Contains("a", "b", "c") // true + _ = list.Contains("a", "b", "c", "d") // false + list.Remove(2) // ["a","b"] + list.Remove(1) // ["a"] + list.Remove(0) // [] + list.Remove(0) // [] (ignored) + _ = list.Empty() // true + _ = list.Size() // 0 + list.Add("a") // ["a"] + list.Clear() // [] +} diff --git a/lists/doublylinkedlist/doublylinkedlist.go b/lists/doublylinkedlist/doublylinkedlist.go index 5192399..ec1843a 100644 --- a/lists/doublylinkedlist/doublylinkedlist.go +++ b/lists/doublylinkedlist/doublylinkedlist.go @@ -141,17 +141,17 @@ func (list *List) Remove(index int) { } } + if element == list.first { + list.first = element.next + } + if element == list.last { + list.last = element.prev + } if element.prev != nil { element.prev.next = element.next - if element == list.last { - list.last = element.prev - } } if element.next != nil { element.next.prev = element.prev - if element == list.first { - list.first = element.next - } } element = nil diff --git a/lists/singlylinkedlist/singlylinkedlist.go b/lists/singlylinkedlist/singlylinkedlist.go new file mode 100644 index 0000000..30d53da --- /dev/null +++ b/lists/singlylinkedlist/singlylinkedlist.go @@ -0,0 +1,223 @@ +/* +Copyright (c) 2015, Emir Pasic +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +// Implementation of doubly linked list. +// Structure is not thread safe. +// References: http://en.wikipedia.org/wiki/Linked_list#Singly_linked_list + +package singlylinkedlist + +import ( + "fmt" + "github.com/emirpasic/gods/lists" + "github.com/emirpasic/gods/utils" + "strings" +) + +func assertInterfaceImplementation() { + var _ lists.Interface = (*List)(nil) +} + +type List struct { + first *element + last *element + size int +} + +type element struct { + value interface{} + next *element +} + +// Instantiates a new empty list +func New() *List { + return &List{} +} + +// Appends a value (one or more) at the end of the list (same as Append()) +func (list *List) Add(values ...interface{}) { + for _, value := range values { + newElement := &element{value: value} + if list.size == 0 { + list.first = newElement + list.last = newElement + } else { + list.last.next = newElement + list.last = newElement + } + list.size++ + } +} + +// Appends a value (one or more) at the end of the list (same as Add()) +func (list *List) Append(values ...interface{}) { + list.Add(values...) +} + +// Prepends a values (or more) +func (list *List) Prepend(values ...interface{}) { + // in reverse to keep passed order i.e. ["c","d"] -> Prepend(["a","b"]) -> ["a","b","c",d"] + for v := len(values) - 1; v >= 0; v-- { + newElement := &element{value: values[v], next: list.first} + list.first = newElement + if list.size == 0 { + list.last = newElement + } + list.size++ + } +} + +// Returns the element at index. +// Second return parameter is true if index is within bounds of the array and array is not empty, otherwise false. +func (list *List) Get(index int) (interface{}, bool) { + + if !list.withinRange(index) { + return nil, false + } + + element := list.first + for e := 0; e != index; e, element = e+1, element.next { + } + + return element.value, true +} + +// Removes one or more elements from the list with the supplied indices. +func (list *List) Remove(index int) { + + if !list.withinRange(index) { + return + } + + if list.size == 1 { + list.Clear() + return + } + + var beforeElement *element + element := list.first + for e := 0; e != index; e, element = e+1, element.next { + beforeElement = element + } + + if element == list.first { + list.first = element.next + } + if element == list.last { + list.last = beforeElement + } + if beforeElement != nil { + beforeElement.next = element.next + } + + element = nil + + list.size-- +} + +// Check if values (one or more) are present in the set. +// All values have to be present in the set for the method to return true. +// Performance time complexity of n^2. +// Returns true if no arguments are passed at all, i.e. set is always super-set of empty set. +func (list *List) Contains(values ...interface{}) bool { + + if len(values) == 0 { + return true + } + if list.size == 0 { + return false + } + for _, value := range values { + found := false + for element := list.first; element != nil; element = element.next { + if element.value == value { + found = true + break + } + } + if !found { + return false + } + } + return true +} + +// Returns all elements in the list. +func (list *List) Values() []interface{} { + values := make([]interface{}, list.size, list.size) + for e, element := 0, list.first; element != nil; e, element = e+1, element.next { + values[e] = element.value + } + return values +} + +// Returns true if list does not contain any elements. +func (list *List) Empty() bool { + return list.size == 0 +} + +// Returns number of elements within the list. +func (list *List) Size() int { + return list.size +} + +// Removes all elements from the list. +func (list *List) Clear() { + list.size = 0 + list.first = nil + list.last = nil +} + +// Sorts values (in-place) using timsort. +func (list *List) Sort(comparator utils.Comparator) { + + if list.size < 2 { + return + } + + values := list.Values() + utils.Sort(values, comparator) + + list.Clear() + + list.Add(values...) + +} + +func (list *List) String() string { + str := "SinglyLinkedList\n" + values := []string{} + for element := list.first; element != nil; element = element.next { + values = append(values, fmt.Sprintf("%v", element.value)) + } + str += strings.Join(values, ", ") + return str +} + +// 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 +} diff --git a/lists/singlylinkedlist/singlylinkedlist_test.go b/lists/singlylinkedlist/singlylinkedlist_test.go new file mode 100644 index 0000000..50c0825 --- /dev/null +++ b/lists/singlylinkedlist/singlylinkedlist_test.go @@ -0,0 +1,138 @@ +/* +Copyright (c) 2015, Emir Pasic +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +package singlylinkedlist + +import ( + "github.com/emirpasic/gods/utils" + "testing" +) + +func TestSinglyLinkedList(t *testing.T) { + + list := New() + + list.Sort(utils.StringComparator) + + list.Add("g", "a") + list.Append("b", "c", "d") + list.Prepend("e", "f") + + shouldBe := []interface{}{"e", "f", "g", "a", "b", "c", "d"} + for i, _ := range shouldBe { + if value, ok := list.Get(i); value != shouldBe[i] || !ok { + t.Errorf("List not populated in correct order. Expected: %v Got: %v", shouldBe, list.Values()) + } + } + + list.Sort(utils.StringComparator) + for i := 1; i < list.Size(); i++ { + a, _ := list.Get(i - 1) + b, _ := list.Get(i) + if a.(string) > b.(string) { + t.Errorf("Not sorted! %s > %s", a, b) + } + } + + list.Clear() + + if actualValue := list.Empty(); actualValue != true { + t.Errorf("Got %v expected %v", actualValue, true) + } + + if actualValue := list.Size(); actualValue != 0 { + t.Errorf("Got %v expected %v", actualValue, 0) + } + + list.Add("a") + list.Add("b", "c") + + if actualValue := list.Empty(); actualValue != false { + t.Errorf("Got %v expected %v", actualValue, false) + } + + if actualValue := list.Size(); actualValue != 3 { + t.Errorf("Got %v expected %v", actualValue, 3) + } + + if actualValue, ok := list.Get(2); actualValue != "c" || !ok { + t.Errorf("Got %v expected %v", actualValue, "c") + } + + list.Remove(2) + + if actualValue, ok := list.Get(2); actualValue != nil || ok { + t.Errorf("Got %v expected %v", actualValue, nil) + } + + list.Remove(1) + list.Remove(0) + + if actualValue := list.Empty(); actualValue != true { + t.Errorf("Got %v expected %v", actualValue, true) + } + + if actualValue := list.Size(); actualValue != 0 { + t.Errorf("Got %v expected %v", actualValue, 0) + } + + list.Add("a", "b", "c") + + //if actualValue := list.Contains("a", "b", "c"); actualValue != true { + // t.Errorf("Got %v expected %v", actualValue, true) + //} + + if actualValue := list.Contains("a", "b", "c", "d"); actualValue != false { + t.Errorf("Got %v expected %v", actualValue, false) + } + + list.Clear() + + //if actualValue := list.Contains("a"); actualValue != false { + // t.Errorf("Got %v expected %v", actualValue, false) + //} + + if actualValue, ok := list.Get(0); actualValue != nil || ok { + t.Errorf("Got %v expected %v", actualValue, false) + } + + if actualValue := list.Empty(); actualValue != true { + t.Errorf("Got %v expected %v", actualValue, true) + } + +} + +func BenchmarkSinglyLinkedList(b *testing.B) { + for i := 0; i < b.N; i++ { + list := New() + for n := 0; n < 1000; n++ { + list.Add(i) + } + for !list.Empty() { + list.Remove(0) + } + } +}