forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackUsingLinkedList.java
More file actions
70 lines (62 loc) · 1.44 KB
/
StackUsingLinkedList.java
File metadata and controls
70 lines (62 loc) · 1.44 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
package com.thealgorithms.stacks;
/**
* A class that implements a Stack using a singly linked list.
* Supports basic operations like push, pop, peek, and isEmpty.
*
* Reference: https://www.geeksforgeeks.org/stack-using-linked-list/
*/
public class StackUsingLinkedList {
/**
* Node class representing each element in the stack
*/
private static class Node {
int data;
Node next;
Node(int data) {
this.data = data;
}
}
private Node top;
/**
* Push an element onto the stack
*
* @param value the value to push
*/
public void push(int value) {
Node newNode = new Node(value);
newNode.next = top;
top = newNode;
}
/**
* Remove and return the top element of the stack
*
* @return top element
*/
public int pop() {
if (top == null) {
throw new RuntimeException("Stack is empty");
}
int value = top.data;
top = top.next;
return value;
}
/**
* Return the top element without removing it
*
* @return top element
*/
public int peek() {
if (top == null) {
throw new RuntimeException("Stack is empty");
}
return top.data;
}
/**
* Check if the stack is empty
*
* @return true if empty, false otherwise
*/
public boolean isEmpty() {
return top == null;
}
}