Commit 67237c0f authored by Jan H. Hosang's avatar Jan H. Hosang Committed by Russ Cox

Implemented ExtendFront/Back functions to insert a list of elements into a list.

R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/181151
parent 9a6b8e21
...@@ -191,3 +191,25 @@ func (l *List) Iter() <-chan interface{} { ...@@ -191,3 +191,25 @@ func (l *List) Iter() <-chan interface{} {
go l.iterate(c) go l.iterate(c)
return c return c
} }
// PushBackList inserts each element of ol at the back of the list.
func (l *List) PushBackList(ol *List) {
last := ol.Back()
for e := ol.Front(); e != nil; e = e.Next() {
l.PushBack(e.Value)
if e == last {
break
}
}
}
// PushFrontList inserts each element of ol at the front of the list. The ordering of the passed list is preserved.
func (l *List) PushFrontList(ol *List) {
first := ol.Front()
for e := ol.Back(); e != nil; e = e.Prev() {
l.PushFront(e.Value)
if e == first {
break
}
}
}
...@@ -134,3 +134,62 @@ func TestList(t *testing.T) { ...@@ -134,3 +134,62 @@ func TestList(t *testing.T) {
checkListPointers(t, l, []*Element{}) checkListPointers(t, l, []*Element{})
checkListLen(t, l, 0) checkListLen(t, l, 0)
} }
func checkList(t *testing.T, l *List, es []interface{}) {
if l.Len() != len(es) {
t.Errorf("list has len=%v, want %v", l.Len(), len(es))
return
}
i := 0
for le := range l.Iter() {
if le != es[i] {
t.Errorf("elt #%d has value=%v, want %v", i, le, es[i])
}
i++
}
}
func TestExtending(t *testing.T) {
l1 := New()
l2 := New()
l1.PushBack(1)
l1.PushBack(2)
l1.PushBack(3)
l2.PushBack(4)
l2.PushBack(5)
l3 := New()
l3.PushBackList(l1)
checkList(t, l3, []interface{}{1, 2, 3})
l3.PushBackList(l2)
checkList(t, l3, []interface{}{1, 2, 3, 4, 5})
l3 = New()
l3.PushFrontList(l2)
checkList(t, l3, []interface{}{4, 5})
l3.PushFrontList(l1)
checkList(t, l3, []interface{}{1, 2, 3, 4, 5})
checkList(t, l1, []interface{}{1, 2, 3})
checkList(t, l2, []interface{}{4, 5})
l3 = New()
l3.PushBackList(l1)
checkList(t, l3, []interface{}{1, 2, 3})
l3.PushBackList(l3)
checkList(t, l3, []interface{}{1, 2, 3, 1, 2, 3})
l3 = New()
l3.PushFrontList(l1)
checkList(t, l3, []interface{}{1, 2, 3})
l3.PushFrontList(l3)
checkList(t, l3, []interface{}{1, 2, 3, 1, 2, 3})
l3 = New()
l1.PushBackList(l3)
checkList(t, l1, []interface{}{1, 2, 3})
l1.PushFrontList(l3)
checkList(t, l1, []interface{}{1, 2, 3})
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment