Repository navigation
Expand file tree
/
Copy pathLinkedListStack.java
More file actions
103 lines (87 loc) · 2.19 KB
/
Copy pathLinkedListStack.java
File metadata and controls
103 lines (87 loc) · 2.19 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
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
import java.util.ArrayList;
/*implementation of a stack using linked list. i.e stack size is dynamic*/
public class LinkedListStack {
public class Node{
private int key;
private String value;
private Node next;
public Node(int key, String value){
this.key = key;
this.value = value;
}
public String toString(){
return "[ (" + key + " , " + value + " )]";
}
}
private Node head;
private Node tail;
public void StackAsLinkedList(){
head = null;
tail = null;
}
public void push(int key, String value){
Node node = new Node(key, value);
if (head == null){
head = node;
tail = node;
} else {
Node temp = head;
head = node;
head.next = temp;
}
System.out.println(String.format("Push : value %s was added to stack", node));
}
public void pushMany(Node[] nodes){
for (Node node : nodes){
push(node.key, node.value);
}
}
public void pop(){
if ( head != null){
System.out.println(String.format("Pop : value %s was removed to stack", head));
head = head.next;
} else {
System.out.println("Sorry but Stack is already empty.");
}
}
public void popAll(){
while (head != null){
pop();
}
}
public void peek(){
if (head != null){
System.out.println(String.format("Peek : value %s is on top of stack", head));
} else {
System.out.println("Sorry but Stack is already empty.");
}
}
public String toString(){
ArrayList<String> list = new ArrayList<String>();
StringBuilder output = new StringBuilder();
System.out.println("Top of the Stack : " + head);
Node currentNode = head;
if (currentNode == null){
return output.toString();
}
while (currentNode != null){
list.add(currentNode.toString());
currentNode = currentNode.next;
}
for (String link : list){
output.append(" --> " + link);
}
return output.toString();
}
public static void main(String [] args){
LinkedListStack theStack = new LinkedListStack();
theStack.push(5, "Data Structures");
theStack.push(9, "Algorithms");
theStack.push(8, "Operating Systems");
theStack.push(7, "Data Mining");
System.out.println(theStack.toString());
theStack.peek();
theStack.pop();
System.out.println(theStack.toString());
}
}