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

Method DelByPos

structure/linkedlist/singlylinkedlist.go:89–119  ·  view source on GitHub ↗

DelByPos deletes the node at the middle based on position in the list and returns its value. Returns false if the list is empty or length is not more than given position

(pos int)

Source from the content-addressed store, hash-verified

87// DelByPos deletes the node at the middle based on position in the list
88// and returns its value. Returns false if the list is empty or length is not more than given position
89func (ll *Singly[T]) DelByPos(pos int) (T, bool) {
90 switch {
91 case ll.Head == nil:
92 var r T
93 return r, false
94 case pos-1 > ll.length:
95 var r T
96 return r, false
97 case pos-1 == 0:
98 return ll.DelAtBeg()
99 case pos-1 == ll.Count():
100 return ll.DelAtEnd()
101 }
102
103 var prev *Node[T]
104 var val T
105 cur := ll.Head
106 count := 0
107
108 for count < pos-1 {
109 prev = cur
110 cur = cur.Next
111 count++
112 }
113
114 val = cur.Val
115 prev.Next = cur.Next
116 ll.length--
117
118 return val, true
119}
120
121// Count returns the current size of the list.
122func (ll *Singly[T]) Count() int {

Callers

nothing calls this directly

Calls 3

DelAtBegMethod · 0.95
CountMethod · 0.95
DelAtEndMethod · 0.95

Tested by

no test coverage detected