# Chapter 7 LinkedList Challenges 5th problem has a more elegant solution

**URL:** <https://forums.kodeco.com/t/chapter-7-linkedlist-challenges-5th-problem-has-a-more-elegant-solution/183582>\
**Category:** Data Structures & Algorithms in Swift\
**Created:** [February 5, 2023, 9:40pm UTC](https://forums.kodeco.com/t/chapter-7-linkedlist-challenges-5th-problem-has-a-more-elegant-solution/183582 "2023-02-05T21:40:15Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![alyakan](https://assets.chunter.kodeco.com/user_avatar/forums.kodeco.com/alyakan/32/105896_2.png) [@alyakan](https://forums.kodeco.com/u/alyakan)\
**Post date:** [February 5, 2023, 9:40pm UTC](https://forums.kodeco.com/t/chapter-7-linkedlist-challenges-5th-problem-has-a-more-elegant-solution/183582/1 "2023-02-05T21:40:15Z")

</div>

First I wanted to say how much I appreciate this book as it sparked an interest in me for data structures and algorithms which I never knew I had!

Anyway, I was able to figure out a nice solution for the 5th problem in chapter 7 which uses only one pointer instead of prev and current:

```auto
extension LinkedList where Value: Equatable {

    public mutating func removeAll(_ valueToRemove: Value) {
        while let head = head, head.value == valueToRemove {
            self.head = head.next
        }

        if head == nil {
            tail = nil
            return
        }

       // At this point, we're sure head.value is not equal to valueToRemove because of the head trimming
        var current = head

        while current?.next != nil {
           // If the next value matches, then remove the next node and do not move the current pointer
            if current?.next?.value == valueToRemove {
                current?.next = current?.next?.next
            } else {
                // otherwise, move the pointer one up
                current = current?.next
            }
        }

        tail = current
    }
}

```
