-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLL.java
150 lines (133 loc) · 2.67 KB
/
LL.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
package LinkedLists;
public class LL implements MyLinkedlist {
private Node head = null;
public void add(int index, Object element) {
Node NEW = new Node();
NEW.setData(element);
if (index == 0) {
head = NEW;
return;
} else {
Node temp = head;
int tempI = 0;
while (temp.getNext() != null) {
if (tempI == index) {
break;
}
tempI++;
temp = temp.getNext();
}
temp.setNext(NEW);
}
}
public void add(Object element) {
Node NEW = new Node();
NEW.setData(element);
if (head == null) {
head = NEW;
} else {
Node temp = head;
while (temp.getNext() != null) {
temp = temp.getNext();
}
temp.setNext(NEW);
}
}
public Object get(int index) {
Node temp = head;
int k = 0;
if (k == index) {
return temp.getData();
}
while (temp != null) {
temp = temp.getNext();
k++;
if (k == index) {
return temp.getData();
}
}
return null;
}
public void set(int index, Object element) {
if (index == 0) {
head.setData(element);
;
return;
} else {
Node temp = head;
int tempI = 0;
while (temp.getNext() != null) {
if (tempI == index) {
break;
}
tempI++;
temp = temp.getNext();
}
temp.setData(element);
}
}
public void clear() {
head = null;
}
public boolean isEmpty() {
return (head == null);
}
public Object remove(int index) {
Node temp = head;
Node prev = head;
if (head == null) {
throw new IndexOutOfBoundsException("Linked list is already null");
}
if (index == 0) {
head = head.getNext();
return prev.getData();
}
int K = 0;
while (temp.getNext() != null) {
prev = temp.getNext();
K++;
if (K == index) {
temp.setNext(temp.getNext().getNext());
return prev.getData();
}
temp = temp.getNext();
}
throw new NullPointerException("Index out of boundaries");
}
public int size() {
if (isEmpty()) {
return 0;
} else {
int S = 0;
Node temp = head;
while (temp != null) {
S++;
temp = temp.getNext();
}
return S;
}
}
public MyLinkedlist sublist(int fromIndex, int toIndex) {
MyLinkedlist sl = new LL();
if(toIndex > this.size()){
throw new RuntimeException("Specified End Index out of boundaries!");
}
for (int i = fromIndex; i <= toIndex; i++) {
sl.add(this.get(i));
}
return sl;
}
public boolean contains(Object o) {
Node temp = head;
if (isEmpty()) {
return false;
}
while (temp != null) {
if (temp.getData() == o) {
return true;
}
temp = temp.getNext();
}
return false;
}
}