-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStackFromLL.java
More file actions
82 lines (70 loc) · 1.84 KB
/
StackFromLL.java
File metadata and controls
82 lines (70 loc) · 1.84 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
package stack.basic;
import linkedList.Basics.SingleLL;
public class StackFromLL {
Node head;
public class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
// push element in stack
public void push(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
return;
}
newNode.next = null;
head = newNode;
}
// pop element in stack
public void pop(int data) {
Node lastNode = head.next;
Node seclastNode = head;
if (head == null) {
System.out.println("empty list");
return;
}
while (lastNode.next != null) {
lastNode = lastNode.next;
seclastNode = seclastNode.next;
}
seclastNode.next = null;
}
// display stack
public void display() {
if (head == null) {
System.out.println("empty list");
}
Node currNode = head;
while (currNode.next != null) {
System.out.print(currNode + " --> ");
currNode = currNode.next;
}
System.out.println("null");
}
// size of stack
public void size() {
Node currNode = head;
int count = 0;
while (currNode.next != null) {
count = count + 1;
}
System.out.println("Size of linkedlist => " + count);
}
public static void main(String[] args) {
SingleLL list = new SingleLL();
list.add(10);
list.add(20);
list.add(30);
list.add(40);
System.out.println("After adding 4 datas : ");
list.display();
list.deleteLast(0);
System.out.println("After deleting 1 data");
list.display();
}
}