-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinkedLists_blueprint.java
158 lines (121 loc) · 3.06 KB
/
LinkedLists_blueprint.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
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
package Linked_Lists;
public class LinkedLists_blueprint {
public Node head;
public Node tail;
public int size;
public class Node {
public int data;
public Node next;
public Node(int data){
this.data = data;
this.next = null;
}
}
// ____________________INSERTION__________________________
public void addFirst(int data){
Node node = new Node(data);
if (head == null) {
head = node;
tail = node;
size = 1;
return;
}
node.next = head;
head = node;
size += 1;
}
public void addLast(int data){
Node node = new Node(data);
if (head == null){
head = node;
tail = node;
size = 1;
return;
}
tail.next = node;
tail = node;
size += 1;
}
public void add(int data, int index){
if (index == 0) {
addFirst(data);
return;
}
if (index == size){
addLast(data);
return;
}
Node temp = head;
int i = 0;
while (i < index-1){
temp = temp.next;
i++;
}
Node node = new Node(data);
node.next = temp.next;
temp.next = node;
size += 1;
}
public Node get(int index){
Node temp = head;
int i =0;
while (i<index){
temp = temp.next;
i++;
}
return temp;
}
// ____________________DELETION__________________________
public int deleteFirst(){
int data = head.data;
if (head == null){
System.out.println("Linked list is empty");
return -1;
}
if (head.next == null){
head = null;
tail = null;
return data;
}
head = head.next;
size--;
return data;
}
public int deleteLast(){
if (head == null){
return deleteFirst();
}
Node prev = get(size-2);
size--;
int data = tail.data;
tail = prev;
tail.next = null;
return data;
}
public int delete(int index){
if (size == 0) {
return deleteFirst();
}
if (index == size-1){
return deleteLast();
}
Node prev = get(index-1);
int data = prev.next.data;
prev.next = prev.next.next;
size--;
return data;
}
public void display(){
Node temp = head;
if (head == null){
System.out.println("Linked list is empty");
return;
}
while (temp != null){
System.out.print(temp.data + " --> ");
temp = temp.next;
}
System.out.println("null");
System.out.println("size is : " + size);
}
}