-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.java
More file actions
76 lines (68 loc) · 1.69 KB
/
Stack.java
File metadata and controls
76 lines (68 loc) · 1.69 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
65
66
67
68
69
70
71
72
73
74
75
76
package ru.spbau.mit.alyokhina;
import org.jetbrains.annotations.NotNull;
/**
* Stack for Calculator
* @param <T> type of stored items
*/
public class Stack<T> {
/** First element in Stack */
Node head = null;
/**
* Add element in Stack
* @param newValue element, which will be add
*/
public void push(@NotNull T newValue) {
Node newHead = new Node();
newHead.value = newValue;
newHead.next = head;
head = newHead;
}
/**
* Delete last added item
* @return item that was deleted or null, if there was no such element
*/
public T pop() {
if (head != null) {
T returnValue = head.value;
head = head.next;
return returnValue;
} else
return null;
}
/**
* last added item
* @return last added item or null if stack is empty
*/
public T peek() {
if (head != null)
return head.value;
else
return null;
}
/**
* Checking the existence of elements in stack
* @return tru, if stack is empty, else - false
*/
public boolean isEmpty() {
return (head == null);
}
/**
* Moves the stack to a string, separated by a space
* @return resulting string
*/
public String toString() {
StringBuilder sb = new StringBuilder();
Node v = head;
while (v != null) {
sb.append((v.value).toString());
sb.append(" ");
v = v.next;
}
return sb.toString();
}
/** Class for Stack. Element of Stack */
private class Node {
private Node next;
private T value;
}
}