import java util NoSuchElementExcepti on public class DLL private clas

  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
import java.util.NoSuchElementException;
public class DLL {
private class Cell {
private Integer value;
private Cell next;
private Cell prev;
private Cell begin;
private Cell end;
public Cell(Integer value) {
this.value = value;
next = null;
prev = null;
begin = null;
end = null;
}
public void setBegin(Cell begin) {
this.begin = begin;
}
public void setEnd(Cell end) {
this.end = end;
}
public Integer getValue() {
return value;
}
public Cell getNext() {
return next;
}
public Cell getPrev() {
return prev;
}
public void setValue(Integer value) {
this.value = value;
}
public void setNext(Cell next) {
this.next = next;
}
public void setPrev(Cell prev) {
this.prev = prev;
}
}
private Cell begin;
private Cell end;
private int size;
public DLL() {
begin = null;
end = null;
size = 0;
}
private Cell getCell(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
} else if (isEmpty()) {
throw new NoSuchElementException();
}
Cell cell = begin;
int s = 0;
while (s < index) {
cell = cell.getNext();
s++;
}
return cell;
}
public void add(int value) {
if (isEmpty()) {
Cell newCell = new Cell(value);
begin = newCell;
end = newCell;
newCell.setBegin(newCell);
newCell.setEnd(newCell);
} else {
Cell newCell = new Cell(value);
end.setNext(newCell);
newCell.setPrev(end);
end.setBegin(null);
end = newCell;
newCell.setBegin(begin);
begin.setEnd(newCell);
}
size++;
}
public int get(int index) {
return getCell(index).getValue();
}
public int indexOf(int value) {
int ans = -1;
Cell cell = begin;
int index = 0;
while (cell != null) {
if (cell.getValue() == value) {
ans = index;
break;
}
cell = cell.getNext();
index++;
}
return ans;
}
public boolean isEmpty() {
return size == 0;
}
public int remove(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
int ans;
Cell cell = getCell(index);
ans = cell.getValue();
Cell prev = cell.getPrev();
Cell next = cell.getNext();
prev.setNext(next);
next.setPrev(prev);
size--;
return ans;
}
public void set(int index, int value) {
Cell cell = getCell(index);
cell.setValue(value);
}
}