-
Notifications
You must be signed in to change notification settings - Fork 317
Expand file tree
/
Copy pathStack.scala
More file actions
64 lines (55 loc) · 1.17 KB
/
Stack.scala
File metadata and controls
64 lines (55 loc) · 1.17 KB
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
/**
* This file is part of Scalacaster project, https://github.com/vkostyukov/scalacaster
* and written by Vladimir Kostyukov, http://vkostyukov.ru
*
* Stack http://en.wikipedia.org/wiki/Stack_(abstract_data_type)
*
* Push - O(1)
* Top - O(1)
* Pop - O(1)
*/
class Stack[+A](self: List[A]) {
/**
* The top of this stack.
*/
def top: A = self.head
/**
* The rest of this stack.
*/
def rest: Stack[A] = new Stack(self.tail)
/**
* Checks whether this stack is empty or not.
*/
def isEmpty: Boolean = self.isEmpty
/**
* Pops top element from this stack.
*
* Time - O(1)
* Space - O(1)
*/
def pop: (A, Stack[A]) = (top, rest)
/**
* Pushes given element 'x' into this stack.
*
* Time - O(1)
* Space - O(1)
*/
def push[B >: A](x: B): Stack[B] = new Stack(x :: self)
}
object Stack {
/**
* Returns an empty stack instance.
*
* Time - O(1)
* Space - O(1)
*/
def empty[A]: Stack[A] = new Stack(Nil)
/**
* Creates a new stack from given 'xs' sequence.
*
* Time - O(n)
* Space - O(1)
*/
def apply[A](xs: A*): Stack[A] =
xs.foldLeft(Stack.empty[A])((r, x) => r.push(x))
}