-
Notifications
You must be signed in to change notification settings - Fork 0
/
CircularLL.java
90 lines (73 loc) · 1.78 KB
/
CircularLL.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
package Linked_Lists;
public class CircularLL {
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;
}
}
// INSERTION
public void addFirst(int data){
Node node = new Node(data);
if (head == null) {
head = node;
tail = node;
size += 1;
return;
}
tail.next = node;
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;
node.next = head;
tail = node;
size += 1;
}
// DELETE USING VALUE
public void delete(int data){
Node node = head;
if (node == null){
return;
}
if (node.data == data){
head = head.next;
tail.next = head;
return;
}
do {
Node n = node.next;
if (n.data == data){
node.next = n.next;
break;
}
node = node.next;
}while (node != head);
}
// DISPLAY
public void display(){
Node node = head;
if (head == null){
System.out.println("LL is empty");
return;
}
do {
System.out.print(node.data + " --> ");
node = node.next;
}while(node != head);
System.out.println(head.data + "(head)");
}
}