MCPcopy Create free account
hub / github.com/TheAlgorithms/Go / ReversePartition

Method ReversePartition

structure/linkedlist/singlylinkedlist.go:142–162  ·  view source on GitHub ↗

ReversePartition Reverse the linked list from the ath to the bth node

(left, right int)

Source from the content-addressed store, hash-verified

140
141// ReversePartition Reverse the linked list from the ath to the bth node
142func (ll *Singly[T]) ReversePartition(left, right int) error {
143 err := ll.CheckRangeFromIndex(left, right)
144 if err != nil {
145 return err
146 }
147 tmpNode := &Node[T]{}
148 tmpNode.Next = ll.Head
149 pre := tmpNode
150 for i := 0; i < left-1; i++ {
151 pre = pre.Next
152 }
153 cur := pre.Next
154 for i := 0; i < right-left; i++ {
155 next := cur.Next
156 cur.Next = next.Next
157 next.Next = pre.Next
158 pre.Next = next
159 }
160 ll.Head = tmpNode.Next
161 return nil
162}
163func (ll *Singly[T]) CheckRangeFromIndex(left, right int) error {
164 if left > right {
165 return errors.New("left boundary must smaller than right")

Callers 1

TestSinglyFunction · 0.80

Calls 1

CheckRangeFromIndexMethod · 0.95

Tested by 1

TestSinglyFunction · 0.64