From 49635e09a3f194c70981fb8340bfafb4f6a7c66d Mon Sep 17 00:00:00 2001 From: surdeus Date: Fri, 21 Jul 2023 20:51:24 +0300 Subject: [PATCH] Implemented swapping for the linked liste. --- src/cmd/ll/main.go | 2 ++ src/llx/main.go | 17 +++++++++++++++++ 2 files changed, 19 insertions(+) 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 {