-
Notifications
You must be signed in to change notification settings - Fork 1
/
tale-of-two-stacks.go
116 lines (95 loc) · 1.59 KB
/
tale-of-two-stacks.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package main
import (
"sync"
"fmt"
)
func main() {
q1 := Queue{stack_newest:NewStack(), stack_oldest:NewStack()}
var q, _type, x int
fmt.Scan(&q)
for i := 0; i < q; i++ {
fmt.Scan(&_type)
if (_type == 1) {
fmt.Scan(&x)
q1.push(x)
} else if (_type == 2) {
q1.pop()
} else {
fmt.Printf("%d\n", q1.front())
}
}
}
type Queue struct {
stack_newest *Stack
stack_oldest *Stack
}
func (q *Queue) push(data int) {
q.stack_newest.pushRune(data)
}
func (q *Queue) pop() {
if (q.stack_oldest.count == 0) {
for q.stack_newest.count > 0 {
q.stack_oldest.pushRune(q.stack_newest.popRune())
}
}
q.stack_oldest.popRune()
}
func (q *Queue) front() int{
if (q.stack_oldest.count == 0) {
for q.stack_newest.count > 0 {
q.stack_oldest.pushRune(q.stack_newest.popRune())
}
}
return q.stack_oldest.peekRune()
}
type stackNode struct {
data int
next *stackNode
}
type Stack struct {
top *stackNode
count int
lock *sync.Mutex
}
func NewNode(item int) *stackNode {
return &stackNode{
data:item,
}
}
func NewStack() *Stack {
s := &Stack{}
s.lock = &sync.Mutex{}
return s
}
func (s *Stack) isEmpty() bool {
return s.top == nil
}
func (s *Stack) peek() int {
s.lock.Lock()
defer s.lock.Unlock()
n := s.top
return n.data
}
func (s *Stack) push(data int) {
s.lock.Lock()
defer s.lock.Unlock()
n := NewNode(data)
if s.top == nil {
s.top = n
} else {
n.next = s.top
s.top = n
}
s.count++
}
func (s *Stack) pop() int {
s.lock.Lock()
defer s.lock.Unlock()
var n *stackNode
if (s.top != nil) {
n = s.top
s.top = n.next
s.count --
}
return n.data
}