Created
October 13, 2013 15:28
-
-
Save dz1984/6963545 to your computer and use it in GitHub Desktop.
Implement the Stack and Queue class through "container/list" package. golang version: 1.2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"container/list" | |
"fmt" | |
"sync" | |
) | |
// Define Stack class | |
type Stack struct { | |
list *list.List | |
lock sync.Mutex | |
} | |
func NewStack() *Stack { | |
return &Stack{list.New(), sync.Mutex{}} | |
} | |
func (this *Stack) Push(elem interface{}) { | |
this.lock.Lock() | |
defer this.lock.Unlock() | |
this.list.PushBack(elem) | |
} | |
func (this *Stack) Pop() (interface{}, bool) { | |
this.lock.Lock() | |
defer this.lock.Unlock() | |
if this.list.Len() == 0 { | |
return nil, false | |
} | |
element := this.list.Back() | |
this.list.Remove(element) | |
return element.Value, true | |
} | |
func (this *Stack) Size() int { | |
this.lock.Lock() | |
defer this.lock.Unlock() | |
return this.list.Len() | |
} | |
func (this *Stack) IsEmpty() bool { | |
this.lock.Lock() | |
defer this.lock.Unlock() | |
return (this.list.Len() == 0) | |
} | |
// Define Queue class | |
type Queue struct { | |
list *list.List | |
lock sync.Mutex | |
} | |
func NewQueue() *Queue { | |
return &Queue{list.New(), sync.Mutex{}} | |
} | |
func (this *Queue) Push(elem interface{}) { | |
this.lock.Lock() | |
defer this.lock.Unlock() | |
this.list.PushFront(elem) | |
} | |
func (this *Queue) Pop() (interface{}, bool) { | |
this.lock.Lock() | |
defer this.lock.Unlock() | |
if this.list.Len() == 0 { | |
return nil, false | |
} | |
element := this.list.Front() | |
this.list.Remove(element) | |
return element.Value, true | |
} | |
func (this *Queue) Size() int { | |
this.lock.Lock() | |
defer this.lock.Unlock() | |
return this.list.Len() | |
} | |
func (this *Queue) IsEmpty() bool { | |
this.lock.Lock() | |
defer this.lock.Unlock() | |
return (this.list.Len() == 0) | |
} | |
func main() { | |
s := NewStack() | |
s.Push(3) | |
if ele, ok := s.Pop(); ok { | |
fmt.Printf("Content : %v\n", ele) | |
fmt.Printf("Size : %d\n", s.Size()) | |
} | |
q := NewQueue() | |
q.Push(4) | |
if ele, ok := q.Pop(); ok { | |
fmt.Printf("Content : %v\n", ele) | |
fmt.Printf("Size : %d\n", s.Size()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment