Федеральное агентство связи ФЕДЕРАЛЬНОЕ ГОСУДАРСТВЕННОЕ БЮДЖЕТНОЕ
ОБРАЗОВАТЕЛЬНОЕ УЧРЕЖДЕНИЕ ВЫСШЕГО ОБРАЗОВАНИЯ «САНКТ-ПЕТЕРБУРГСКИЙ ГОСУДАРСТВЕННЫЙ УНИВЕРСИТЕТ ТЕЛЕКОММУНИКАЦИЙ ИМ. ПРОФ. М. А. БОНЧ-БРУЕВИЧА» (СПбГУТ)
Факультет инфокоммуникационных сетей и систем Кафедра программной инженерии и вычислительной техники
ЛАБОРАТОРНАЯ РАБОТА №4
по дисциплине «Разработка Java-приложений управления телекоммуникациями»
Выполнил: студент 3-го курса дневного отделения группы ИКПИ-85
Коваленко Леонид Александрович Преподаватель:
доцент кафедры ПИиВТ Белая Татьяна Иоанновна
Санкт-Петербург
2020
Цель работы Ознакомиться с механизмом систем ввода и вывода данных.
Создадим циклический двусвязный список CircularLinkedList с выделенной головой (т. е. голова не хранит значение, а «пустой» список состоит из одной головы, замкнутой на себя), в котором будут реализованы следующие методы:
—конструктор с параметром n — числом элементов;
—метод добавления элемента;
—метод удаления элемента;
—методы получения и изменения значения элемента списка по
индексу.
Также реализуем оптимизацию скорости доступа: внутри экземпляра списка будет храниться ссылка-узел и его номер, к которому производилось предыдущее обращение, а методы доступа (методы получения и изменения значения) к узлу по его номеру (а также методы добавления и удаления) должны двигаться к заданному узлу от ближайшего элемента: от предыдущего узла, от головы вперед, от головы назад (от хвоста).
Кроме того, создадим файл CircularLinkedListTest.java для проверки работы класса CircularLinkedList. Коды этих двух файлов приведены в табл. 1, 2.
Таблица 1 — Код vectors/CircularLinkedList.java package vectors;
public class CircularLinkedList implements IVector { // Конструктор
public CircularLinkedList(int n) {
current = head = new Node(0, null, null); head.prev = head.next = head; current_index = -1;
if (n > 0) {
Node temp = head;
for (int i = 0; i < n; ++i) {
temp = (temp.next = new Node(0, temp, null));
}
temp.next = head; head.prev = temp; size = n;
} else {
2
size = 0;
}
}
// Получение элемента по индексу
public double get(int i) throws VectorIndexOutOfBoundsException { if (i >= 0 && i < size) {
if (Math.abs(i - current_index) > Math.min(i + 1, size - i)) { current = head;
current_index = (i + i < size) ? -1 : size;
}
for (; current_index < i; ++current_index) { current = current.next;
}
for (; current_index > i; --current_index) { current = current.prev;
}
return current.value;
}
throw new VectorIndexOutOfBoundsException("VectorIndexOutOfBoundsException", i);
}
// Изменение значения элемента по индексу public void set(int i, double value) throws
VectorIndexOutOfBoundsException { if (i >= 0 && i < size) {
if (Math.abs(i - current_index) > Math.min(i + 1, size - i)) { current = head;
current_index = (i + i < size) ? -1 : size;
}
for (; current_index < i; ++current_index) { current = current.next;
}
for (; current_index > i; --current_index) { current = current.prev;
}
current.value = value; return;
}
throw new VectorIndexOutOfBoundsException("VectorIndexOutOfBoundsException", i);
}
//Получение длины списка public int size() {
return size;
}
//Добавление элемента в список
public void add(int i, double elem) throws VectorIndexOutOfBoundsException {
if (i >= 0 && i <= size) {
if (Math.abs(i - current_index) > Math.min(i + 1, size - i)) { current = head;
current_index = (i + i < size) ? -1 : size;
}
for (; current_index < i; ++current_index) { current = current.next;
}
for (; current_index > i; --current_index) { current = current.prev;
}
current = current.prev;
current.next = new Node(elem, current, current.next);
3
current.next.next.prev = current.next; current = current.next;
++size; return;
}
throw new VectorIndexOutOfBoundsException("VectorIndexOutOfBoundsException", i);
}
// Удаление элемента из списка
public void remove(int i) throws VectorIndexOutOfBoundsException { if (i >= 0 && i < size) {
if (Math.abs(i - current_index) > Math.min(i + 1, size - i)) { current = head;
current_index = (i + i < size) ? -1 : size;
}
for (; current_index < i; ++current_index) { current = current.next;
}
for (; current_index > i; --current_index) { current = current.prev;
}
current = current.prev; current.next = current.next.next; current.next.prev = current; current = current.next;
--size; return;
}
throw new VectorIndexOutOfBoundsException("VectorIndexOutOfBoundsException", i);
}
//Нахождение нормы Евклида public double normEuclidean() {
double r = 0;
for (Node temp = head.next; temp != head; temp = temp.next) { r += temp.value * temp.value;
}
return Math.sqrt(r);
}
//Вывод всех элементов списка
public void print() { Node temp = head.next; if (temp != head) {
System.out.print(temp.value); temp = temp.next;
}
for (; temp != head; temp = temp.next) { System.out.print(" " + temp.value);
}
System.out.println();
}
// Вывод всех элементов списка в обратном порядке public void rprint() {
Node temp = head.prev; if (temp != head) {
System.out.print(temp.value); temp = temp.prev;
}
for (; temp != head; temp = temp.prev) { System.out.print(" " + temp.value);
}
4
System.out.println();
}
// Класс "Узел"
public static class Node {
public Node(double value, Node prev, Node next) { this.value = value;
this.prev = prev; this.next = next;
}
public double value; public Node prev, next;
}
private Node head, current; private int size, current_index;
}
Таблица 2 — Код CircularLinkedListTest.java
import vectors.CircularLinkedList;
import vectors.VectorIndexOutOfBoundsException;
public class CircularLinkedListTest {
public static void main(String[] args) throws VectorIndexOutOfBoundsException {
CircularLinkedList list = new CircularLinkedList(10); System.out.print("Source list (10 elements): "); list.print();
System.out.println("\nMethod \'set\'. list.set(0, 1) and list.set(list.size() - 1, 10)");
list.set(0, 1); list.set(list.size() - 1, 10); System.out.print("New list: "); list.print();
System.out.print("Reversed new list: "); list.rprint(); System.out.println("\nMethod \'get\'.");
System.out.println("list.get(0): " + list.get(0)); System.out.println("list.get(list.size() - 1): " +
list.get(list.size() - 1));
System.out.print("\nMethod \'set\'. Ordered list: "); for (int i = 0, len = list.size(); i < len; ++i) {
list.set(i, i);
}
list.print();
System.out.print("Reverse ordered list: "); list.rprint();
System.out.print("Test of method \'get\': "); boolean flag = true;
for (int i = 0, len = list.size(); i < 10000000; ++i) { int k = (int) Math.random() * len;
if (list.get(k) != k) { flag = false; break;
}
}
System.out.println(flag ? "it works" : "this does not work"); System.out.println("\nMethod \'add\'."); System.out.println("list.add(0, -1) and list.add(list.size(), 10)"); list.add(0, -1);
list.add(list.size(), 10); System.out.print("List: "); list.print();
5