[Go] 자료구조 구현

natae·2022년 8월 10일
1

Golang

목록 보기
1/11

개요

코드

list.go

// go 1.18
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

// go 1.18
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

// go 1.18
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)
}
profile
서버 프로그래머

0개의 댓글