-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeleteLinkedList.java
More file actions
125 lines (114 loc) · 3.2 KB
/
DeleteLinkedList.java
File metadata and controls
125 lines (114 loc) · 3.2 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
class Node<T>{
T data;
Node<T> next;
public Node(T data){
this.data = data;
this.next = null;
}
}
class SinglyLinkedList<T>{
public Node<T> head;
public SinglyLinkedList(){
this.head = null;
}
public boolean isEmpty(){
return head == null;
}
public int getSize(){
int count = 0;
Node<T> current = head;
while (current != null) {
count++;
current = current.next;
}
return count;
}
public void insertAtFront(T data) {
Node<T> newNode = new Node<>(data);
if (isEmpty()) {
head = newNode;
} else {
newNode.next = head;
head = newNode;
}
}
public void insertAtEnd(T data) {
Node<T> newNode = new Node<>(data);
if (isEmpty()) {
head = newNode;
} else {
Node<T> current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
}
public void deleteAtFront() {
if (isEmpty()) {
System.out.println("Linked list is empty");
} else {
head = head.next;
}
}
public void deleteAtEnd() {
if (isEmpty()) {
System.out.println("Linked list is empty");
} else if (head.next == null) {
head = null;
} else {
Node<T> current = head;
Node<T> previous = null;
while (current.next != null) {
previous = current;
current = current.next;
}
previous.next = null;
}
}
public void display() {
if (isEmpty()) {
System.out.println("Linked list is empty");
} else {
Node<T> current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
}
}
public class DeleteLinkedList{
public static void main(String args[]){
SinglyLinkedList<Object> anytypeLinkedList = new SinglyLinkedList<>();
anytypeLinkedList.insertAtFront("Mango");
anytypeLinkedList.insertAtFront(4);
anytypeLinkedList.insertAtEnd('a');
anytypeLinkedList.insertAtEnd(2.03);
anytypeLinkedList.display();
Object key = 4;
deleteKey(anytypeLinkedList, key);
System.out.println("After deleting key = " + key + " , now linked list: ");
anytypeLinkedList.display();
}
public static <T> void deleteKey(SinglyLinkedList<T> linkedList, T key){
if(linkedList.isEmpty()){
System.out.print("linked list is empty.");
return;
}
if(linkedList.head.data == key){
linkedList.deleteAtFront();
return;
}
Node<T> current = linkedList.head;
while(current.next != null){
if(current.next.data == key){
current.next = current.next.next;
return;
}
current = current.next;
}
System.out.println("Key is not found.");
}
}