-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathCircularLinkedList.java
More file actions
99 lines (82 loc) · 2.04 KB
/
CircularLinkedList.java
File metadata and controls
99 lines (82 loc) · 2.04 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
public class CircularLinkedList {
private Node head;
private Node tail;
public CircularLinkedList() {
this.head = null;
this.tail = null;
}
public boolean isEmpty() {
return head == null;
}
public void insertAtBeginning(int data) {
Node newNode = new Node(data);
if (isEmpty()) {
head = newNode;
tail = newNode;
newNode.next = newNode;
} else {
newNode.next = head;
head = newNode;
tail.next = newNode;
}
}
public void insertAtEnd(int data) {
Node newNode = new Node(data);
if (isEmpty()) {
head = newNode;
tail = newNode;
newNode.next = newNode;
} else {
newNode.next = tail.next;
tail.next = newNode;
tail = newNode;
}
}
public void deleteAtBeginning() {
if (isEmpty()) {
return;
}
if (head == tail) {
head = null;
tail = null;
} else {
head = head.next;
tail.next = head;
}
}
public void deleteAtEnd() {
if (isEmpty()) {
return;
}
if (head == tail) {
head = null;
tail = null;
} else {
Node currentNode = head;
while (currentNode.next != tail) {
currentNode = currentNode.next;
}
tail = currentNode;
tail.next = head;
}
}
public void printList() {
Node currentNode = head;
while (currentNode != null) {
System.out.print(currentNode.data + " ");
currentNode = currentNode.next;
if (currentNode == head) {
break;
}
}
System.out.println();
}
private class Node {
private int data;
private Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
}