github.com/djordje200179/extendedlibrary/datastructures@v1.7.1-0.20240227175559-d09520a92dd4/cols/linklist/iterator.go (about)

     1  package linklist
     2  
     3  // Iterator is an iterator over a List.
     4  type Iterator[T any] struct {
     5  	list *List[T]
     6  
     7  	curr  *Node[T]
     8  	index int
     9  }
    10  
    11  // Valid returns true if the iterator is currently pointing to a valid element.
    12  func (it *Iterator[T]) Valid() bool {
    13  	return it.curr != nil
    14  }
    15  
    16  // Move moves the iterator to the next element.
    17  func (it *Iterator[T]) Move() {
    18  	if it.curr == nil {
    19  		return
    20  	}
    21  
    22  	it.curr = it.curr.next
    23  	it.index++
    24  }
    25  
    26  // GetRef returns a reference to the current element.
    27  func (it *Iterator[T]) GetRef() *T {
    28  	return &it.curr.Value
    29  }
    30  
    31  // Get returns the current element.
    32  func (it *Iterator[T]) Get() T {
    33  	return it.curr.Value
    34  }
    35  
    36  // Set sets the current element.
    37  func (it *Iterator[T]) Set(value T) {
    38  	it.curr.Value = value
    39  }
    40  
    41  // InsertBefore inserts the specified element before the current element.
    42  // Iterator then points to the inserted element.
    43  func (it *Iterator[T]) InsertBefore(value T) {
    44  	it.curr.InsertBefore(value)
    45  	it.curr = it.curr.prev
    46  }
    47  
    48  // InsertAfter inserts the specified element after the current element.
    49  // Iterator keeps pointing to the current element.
    50  func (it *Iterator[T]) InsertAfter(value T) {
    51  	it.curr.InsertAfter(value)
    52  }
    53  
    54  // Remove removes the current element.
    55  // Iterator then points to the next element.
    56  func (it *Iterator[T]) Remove() {
    57  	next := it.curr.next
    58  	it.list.RemoveNode(it.curr)
    59  	it.curr = next
    60  }
    61  
    62  // Node returns the current node.
    63  func (it *Iterator[T]) Node() *Node[T] {
    64  	return it.curr
    65  }
    66  
    67  // Index returns the current index.
    68  func (it *Iterator[T]) Index() int {
    69  	return it.index
    70  }