-
Notifications
You must be signed in to change notification settings - Fork 0
/
SLL.java
57 lines (47 loc) · 1.1 KB
/
SLL.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
public class SLL {
Node head;
Node tail;
int size;
SLL(){
head = new Node(-100);
tail = new Node(-100);
head.next = tail;
}
void addToFront(int i){
Node n = new Node(i);
n.next = head.next;
head.next = n;
size++;
}
void addToBack(int i){
Node cur = head;
Node n = new Node(i);
n.next = tail;
while(cur.next != tail){
cur = cur.next;
}
cur.next = n;
size++;
}
int findX(int x){
int curPosition = 0;
Node cur = head; //references the beginning of the list
while (cur.next != null){
if(cur.data == x){
return curPosition;
}
cur = cur.next;
curPosition++;
}
return -1;
}
public static void main(String[] args){
SLL myList = new SLL();
myList.addToFront(2);
myList.addToFront(5);
myList.addToFront(4);
myList.addToFront(3);
myList.addToFront(8);
System.out.println(myList.findX(2));
}
}