forked from kbeathanabhotla/DSAAJ2-Answers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Chap03.question.30.SelfAdjustingList.java
115 lines (104 loc) · 3.22 KB
/
Chap03.question.30.SelfAdjustingList.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
//Chap03.question.30.SelfAdjustingList.java
public class SelfAdjustingList {
}
class SelfAdjustingListArray<T> {
private Object[] elements;
private int size, capacity;
public SelfAdjustingListArray(int c) {
capacity = c > 10 ? c : 10;
size = 0;
elements = new Object[capacity];
}
public void add(T t) {
if (size == capacity) {
capacity = capacity + capacity >>> 1;
Object[] arr = new Object[capacity];
System.arraycopy(elements, 0, arr, 0, size);
elements = arr;
}
elements[size++] = t;
}
public boolean find(T t) {
if (t == null) {
for (int i = 0; i < size; i++) {
if (elements[i] == null) {
System.arraycopy(elements, i + 1, elements, i, size - i - 1);
elements[size - 1] = null;
return true;
}
}
} else {
for (int i = 0; i < size; i++) {
if (t.equals(elements[i])) {
System.arraycopy(elements, i + 1, elements, i, size - i - 1);
elements[size - 1] = t;
return true;
}
}
}
return false;
}
}
class SelfAdjustingListLinkedList<T> {
private Node<T> head, tail;
public SelfAdjustingListLinkedList() {
head = new Node<>(null, null, null);
tail = new Node<>(null, null, null);
head.next = tail;
tail.prev = head;
}
public void add(T t) {
Node<T> before = tail.prev;
Node<T> node = new Node<>(null, t, null);
before.next = node;
node.next = tail;
tail.prev = node;
node.prev = before;
}
public boolean find(T t) {
Node<T> cursor = head.next;
if (t == null) {
while (cursor != tail) {
if (cursor.data == null) {
Node<T> before = cursor.prev;
Node<T> after = cursor.next;
before.next = after;
after.prev = before;
Node<T> before1 = tail.prev;
before1.next = cursor;
cursor.next = tail;
tail.prev = cursor;
cursor.prev = before1;
return true;
}
cursor = cursor.next;
}
} else {
while (cursor != tail) {
if (t.equals(cursor.data)) {
Node<T> before = cursor.prev;
Node<T> after = cursor.next;
before.next = after;
after.prev = before;
Node<T> before1 = tail.prev;
before1.next = cursor;
cursor.next = tail;
tail.prev = cursor;
cursor.prev = before1;
return true;
}
cursor = cursor.next;
}
}
return false;
}
private static class Node<T> {
T data;
Node<T> prev, next;
Node(Node<T> p, T t, Node<T> n) {
data = t;
prev = p;
next = n;
}
}
}