-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedList remove last element.java
More file actions
65 lines (62 loc) · 1.59 KB
/
LinkedList remove last element.java
File metadata and controls
65 lines (62 loc) · 1.59 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
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
public class LinkedList {
Node head = null;
public void add(int element) {
Node newNode = new Node(element);
if (head == null) {
head = newNode;
} else {
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
}
}
public void removeLast() {
if (head == null) {
System.out.println("List is already empty.");
return;
}
if (head.next == null) {
head = null;
return;
}
Node temp = head;
while (temp.next.next != null) {
temp = temp.next;
}
temp.next = null;
}
public void display() {
if (head == null) {
System.out.println("List is empty.");
return;
}
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " -> ");
temp = temp.next;
}
System.out.println("NULL");
}
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.add(5);
list.add(10);
list.add(15);
list.add(20);
System.out.println("Original Linked List:");
list.display();
list.removeLast();
System.out.println("\nAfter removing last element:");
list.display();
}
}