-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedList.java
119 lines (104 loc) · 2.56 KB
/
LinkedList.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
package business_analyzer_assignment;
import java.util.*;
public class LinkedList<T> implements List<T> {
Node<T> head;
private Node<T> tail;
int size;
public LinkedList() {
head = new Node<>(null);
tail = null;
size = 0;
}
/**
* Method adds new element to the linkedlist
* @param item the item to be added
*/
@Override
public void add(T item) {
Node<T> node = new Node<>(item);
if (tail == null) {
head = node;
tail = node;
} else {
tail.next = node;
tail = node;
}
size++;
}
/**
* Method returns the size of the linkedlist
* @return size
*/
@Override
public int size() {
return size;
}
@Override
public Iterator<T> iterator() {
return null;
}
@Override
public ListIterator<T> listIterator() {
return null;
}
public static class LinkedListIterator<T> implements Iterator<T> {
private Node<T> current;
public LinkedListIterator(Node<T> head) {
current = head;
}
@Override
public boolean hasNext() {
return current != null;
}
@Override
public T next() {
T data = current.getData();
current = current.getNext();
return data;
}
public Iterator<T> iterator() {
return new LinkedListIterator<>(current);
}
}
/**
* Method checks if the linkedlist contains a value
* @param data the item to be checked
* @return boolean value
*/
@Override
public boolean contains(T data) {
Node<T> current = head;
while (current != null) {
if (current.getData().equals(data)) {
return true;
}
current = current.getNext();
}
return false;
}
/**
* Method to get the value at a particular position
* @param index index in the list
* @return T
*/
@Override
public T get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
Node<T> current = head;
for (int i = 0; i < index; i++) {
current = current.getNext();
}
return current.getData();
}
public Node<T> getNode(int pos) {
if(pos<0 || pos>=size)
return null;
Node<T> prev = head;
for(int i=0; i<size; i++){
prev = prev.next;
}
return prev;
}
}