-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackUsingLinkList.java
More file actions
executable file
·51 lines (40 loc) · 1.11 KB
/
Copy pathStackUsingLinkList.java
File metadata and controls
executable file
·51 lines (40 loc) · 1.11 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
package com.codeWithArsalon.LinearDS;
import java.util.NoSuchElementException;
public class StackUsingLinkList {
private Node first;
private Node last;
private int size;
private class Node { //embedded class "implementation detail"
int value;
private Node next;
public Node (int value){ //constructor w/in the Node class
this.value = value;
}
}
public void push(int item){ //addFirst() from LinkedList / O(1) operation
var node = new Node(item);
if(isEmpty())
first = last = node;
node.next = first;
first = node;
size++;
}
public Node pop(){ //removeFirst() from LinkedList O(1) operation
if(isEmpty())
throw new NoSuchElementException();
else {
var top = first;
var second = first.next;
first.next = null;
first = second;
size--;
return top;
}
}
public void peek() {
System.out.println(first.value);
}
private boolean isEmpty() {
return first == null;
}
}