diff --git a/src/cmd/ll/main.go b/src/cmd/ll/main.go index a28d7ec..7d8c709 100644 --- a/src/cmd/ll/main.go +++ b/src/cmd/ll/main.go @@ -15,6 +15,8 @@ func main() { ll.Append("four") ll.Push("minus one") + ll.Swap(1, 3) + for p := range ll.Chan() { fmt.Println(p.K, p.V) } diff --git a/src/llx/main.go b/src/llx/main.go index a0f5777..c6b0c87 100644 --- a/src/llx/main.go +++ b/src/llx/main.go @@ -75,6 +75,23 @@ func (ll *LinkedList[V]) Set(i int, v V) (bool) { return true } +func (ll *LinkedList[V]) Swap(i1, i2 int) { + if i1 == i2 { + return + } + + max := ll.ln - 1 + if i1 < 0 || i2 < 0 || i1 > max || i2 > max { + panic("index out of range") + } + + el1, _ := ll.GetEl(i1) + el2, _ := ll.GetEl(i2) + + el1.value, el2.value = + el2.value, el1.value +} + // Deletes the element by its index. func (ll *LinkedList[V]) Delete(i int) (bool) { if ll.ln <= i {