forked from avilanicolas/Crazy8
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLStack.java
105 lines (96 loc) · 2.35 KB
/
LStack.java
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
package Crazy8;
import java.util.LinkedList;
import java.util.Iterator;
import java.lang.Comparable;
/**
* LSTack useses the LinkedList methods and structure to recreate
* a stack class for Java. This remasks, effectively, some of the
* methods as more accessible one, and conforms to the general idea
* of what a stack is.
*/
public class LStack<T>
{
LinkedList<T> stack = new LinkedList<T>();
int size = 0;
public void LStack()
{
// do nothing
}
/**
* @return A boolean telling if the stack is empty or not.
*/
public boolean isEmpty()
{
// An empty stack can be determined if .peek() returns
// a null value or not.
boolean ret = false;
if(stack.peek() == null)
{
ret = true;
}
return ret;
}
/**
* Iterate through the stack for the desired element.
* @return An int containing the index of a found element. -1 if it is not discovered.
*/
public int search(T key)
{
Iterator iter = stack.listIterator();
int i = -1;
boolean found = false;
while(iter.hasNext() && !found)
{
i++;
if(iter.next() == key)
{
found = true;
}
}
// If found, i, else, -1
return (found) ? i : -1;
}
/**
* The stack push method.
* @param value The value to push.
*/
public void push(T value)
{
this.size++;
stack.push(value);
}
/**
* The stack pop method.
* @return The popped item.
*/
public T pop()
{
this.size--;
return stack.pop();
}
/**
* The stack peek method.
* @return The top of the stack.
*/
public T peek()
{
return stack.peek();
}
/**
* Get the value of an item at a certain index with the stack.
* NOTE: Stack indices begin from 1, not zero.
* @param index The index in the stack you want to get.
* @return The item at the specified index.
*/
public T get(int index)
{
T ret = null;
// If the given index is
if(index <= size && index >= 1 && !stack.isEmpty())
{
// This the LinkedList method .get()
ret = stack.get(index - 1);
}
return ret;
}
}