-
Notifications
You must be signed in to change notification settings - Fork 0
/
CyclicLinkedListAddDelete
86 lines (75 loc) · 2.05 KB
/
CyclicLinkedListAddDelete
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
class ListNode {
public ListNode next;
public Object data;
public ListNode(Object data, ListNode next) {
this.next = next;
this.data = data;
}
}
class CircularLinkedList {
private ListNode head = null;
private int numberOfElements = 0;
private ListNode actualElement = null;
private int index = 0;
public boolean isEmpty() {
return (numberOfElements == 0);
}
public int getNumberOfElements() {
return numberOfElements;
}
public void insertFirst(Object data) {
if (!(isEmpty())) {
index++;
}
ListNode listNode = new ListNode(data, head);
head = listNode;
numberOfElements++;
}
public void insertAfterActual(Object data) {
ListNode listNode = new ListNode(data, actualElement.next);
actualElement.next = listNode;
numberOfElements++;
}
public boolean deleteFirst() {
if (isEmpty())
return false;
if (index > 0)
index--;
head = head.next;
numberOfElements--;
return true;
}
public boolean deleteActualElement() {
if (index > 0) {
numberOfElements--;
index--;
ListNode listNode = head;
while (listNode.next.equals(actualElement) == false)
listNode = listNode.next;
listNode.next = actualElement.next;
actualElement = listNode;
return true;
}
else {
actualElement = head.next;
index = 0;
return deleteFirst();
}
}
public boolean goToNextElement() {
if (isEmpty())
return false;
index = (index + 1) % numberOfElements;
if (index == 0)
actualElement = head;
else
actualElement = actualElement.next;
return true;
}
public Object getActualElementData() {
return actualElement.data;
}
public void setActualElementData(Object data) {
actualElement.data = data;
}
}