-
Notifications
You must be signed in to change notification settings - Fork 381
/
Copy pathLinkedListDeletions.java
65 lines (44 loc) · 1.12 KB
/
LinkedListDeletions.java
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
package com.anurag;
public class LL {
private Node head;
private Node tail;
private int size;
public LL() {
this.size = 0;
}
//----------------DELETION----------------->>>>>>>>>>
//DELETE ELEMENT AT FIRST
public int deleteFirst(){
int val = head.value;
head = head.next;
if(head == null){
tail = null;
}
size--;
return val;
}
//DELETE ELEMENT AT LAST
public int deleteLast(){
if(size <= 1){
return deleteFirst();
}
Node secondLast = get(size - 2);
int val = tail.value;
tail = secondLast;
tail.next = null;
return val;
}
//DELETE ELEMENT AT A PARTICULAR INDEX
public int delete(int index){
if(index == 0){
return deleteFirst();
}
if(index == size-1){
return deleteLast();
}
Node prev = get(index - 1); //prev is the previous element from the element that's to be removed
int val = prev.next.value;
prev.next = prev.next.next;
return val;
}
}