개요
- golang에서 네이티브로 지원하지 않는 자료구조를 간단히 구현
- 다양한 타입 지원을 위해 빈 인터페이스 사용
코드
list.go
package algorithm
type IList interface {
Add(data interface{})
Remove(data interface{}) int
Exist(data interface{}) int
ToSlice() []interface{}
Count() int
}
type MyList struct {
slice []interface{}
}
func NewList() IList {
return &MyList{
slice: make([]interface{}, 0),
}
}
func NewListWithCap(cap int) IList {
return &MyList{
slice: make([]interface{}, 0, cap),
}
}
func (l *MyList) Add(val interface{}) {
l.slice = append(l.slice, val)
}
func (l *MyList) Remove(val interface{}) int {
index := l.Exist(val)
if index >= 0 {
copy(l.slice[index:], l.slice[index+1:])
l.slice = l.slice[:len(l.slice)-1]
}
return index
}
func (l *MyList) Exist(val interface{}) int {
for i, val := range l.slice {
if val == val {
return i
}
}
return -1
}
func (l *MyList) ToSlice() []interface{} {
return l.slice
}
func (l *MyList) Count() int {
return len(l.slice)
}
stack.go
package algorithm
type IStack interface {
Push(data interface{})
Pop() interface{}
Count() int
}
type MyStack struct {
slice []interface{}
}
func NewStack() IStack {
return &MyStack{
slice: make([]interface{}, 0),
}
}
func NewStackWithCap(cap int) IStack {
return &MyStack{
slice: make([]interface{}, 0, cap),
}
}
func (s *MyStack) Push(val interface{}) {
s.slice = append(s.slice, val)
}
func (s *MyStack) Pop() interface{} {
if len(s.slice) == 0 {
return nil
}
val := s.slice[len(s.slice)-1]
s.slice = s.slice[:len(s.slice)-1]
return val
}
func (s *MyStack) Count() int {
return len(s.slice)
}
queue.go
package algorithm
type IQueue interface {
Enqueue(data interface{})
Dequeue() interface{}
Count() int
}
type MyQueue struct {
slice []interface{}
}
func NewQueue() IQueue {
return &MyQueue{
slice: make([]interface{}, 0),
}
}
func NewQueueWithCap(cap int) IQueue {
return &MyQueue{
slice: make([]interface{}, 0, cap),
}
}
func (q *MyQueue) Enqueue(val interface{}) {
q.slice = append(q.slice, val)
}
func (q *MyQueue) Dequeue() interface{} {
if len(q.slice) == 0 {
return nil
}
val := q.slice[0]
q.slice = q.slice[1:]
return val
}
func (q *MyQueue) Count() int {
return len(q.slice)
}