1
0
mirror of https://github.com/golang/go synced 2024-11-23 08:40:08 -07:00

container/list: combining insert and remove operations while moving elements within a list.

Methods MoveToFront, MoveToBack, MoveBefore and MoveAfter remove the given element from the list and later add the same element at a desired position. This has resulted in some inefficiencies, with remove method making 4 unncessary operations and insert method making 2. The commit merges these two methods into a method called move.

Fixes #27747
This commit is contained in:
Raghavendra Nagaraj 2018-10-26 17:40:49 +05:30
parent 2d77600ae7
commit c614e91e23

View File

@ -116,6 +116,23 @@ func (l *List) remove(e *Element) *Element {
return e
}
// move moves e to next to at and returns e.
func (l *List) move(e, at *Element) *Element {
if e == at {
return e
}
e.prev.next = e.next
e.next.prev = e.prev
n := at.next
at.next = e
e.prev = at
e.next = n
n.prev = e
return e
}
// Remove removes e from l if e is an element of list l.
// It returns the element value e.Value.
// The element must not be nil.
@ -170,7 +187,7 @@ func (l *List) MoveToFront(e *Element) {
return
}
// see comment in List.Remove about initialization of l
l.insert(l.remove(e), &l.root)
l.move(e, &l.root)
}
// MoveToBack moves element e to the back of list l.
@ -181,7 +198,7 @@ func (l *List) MoveToBack(e *Element) {
return
}
// see comment in List.Remove about initialization of l
l.insert(l.remove(e), l.root.prev)
l.move(e, l.root.prev)
}
// MoveBefore moves element e to its new position before mark.
@ -191,7 +208,7 @@ func (l *List) MoveBefore(e, mark *Element) {
if e.list != l || e == mark || mark.list != l {
return
}
l.insert(l.remove(e), mark.prev)
l.move(e, mark.prev)
}
// MoveAfter moves element e to its new position after mark.
@ -201,7 +218,7 @@ func (l *List) MoveAfter(e, mark *Element) {
if e.list != l || e == mark || mark.list != l {
return
}
l.insert(l.remove(e), mark)
l.move(e, mark)
}
// PushBackList inserts a copy of an other list at the back of list l.