Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Last active September 7, 2025 08:35
Show Gist options
  • Save sunmeat/9cbcc3bc3b2aa344c81321e898c37e14 to your computer and use it in GitHub Desktop.
Save sunmeat/9cbcc3bc3b2aa344c81321e898c37e14 to your computer and use it in GitHub Desktop.
java singly linked list example
package collections;
class SinglyLinkedList {
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
private Node head;
private Node tail;
private int count;
public SinglyLinkedList() {
// тут нічого робити...
}
/**
* приклад коментаря документації! метод під коментарем реалізує
* додавання елемента на початок списку.
* <br />
* <h2>величезний заголовок</h2>
* <h3>дуже великий заголовок</h3>
* <hr />
* <h4>великий заголовок</h4>
* <h5>звичайний заголовок</h5>
* <h6>маленький заголовок</h6>
* <ul>
* <li>інкапсуляція</li>
* <li>спадкування</li>
* <li>поліморфізм</li>
* </ul>
*
* @see java.lang.String
* @return метод нічого не повертає...
* @see <a href="https://t.me/sunmeat">Alexander ©</a>
*/
public void addHead(int data) {
Node newElem = new Node(data);
newElem.next = head;
head = newElem;
if (count == 0) {
tail = newElem;
}
count++;
}
// додавання елемента в кінець списку
public void addTail(int data) {
Node newElem = new Node(data);
if (count == 0) {
head = newElem;
tail = newElem;
} else {
tail.next = newElem;
tail = newElem;
}
count++;
}
// вставка елемента за позицією
public void insert(int data, int position) {
if (position <= 0 || count == 0) {
addHead(data);
return;
}
if (position >= count) {
addTail(data);
return;
}
Node newElem = new Node(data);
Node beforeNew = getNodeAt(position - 1);
newElem.next = beforeNew.next;
beforeNew.next = newElem;
count++;
}
// видалення першого елемента
public void delHead() {
if (count == 0) {
return;
}
head = head.next;
count--;
if (count == 0) {
tail = null;
}
}
// видалення останнього елемента
public void delTail() {
if (count == 0) {
return;
}
if (count == 1) {
delHead();
return;
}
Node beforeLast = getNodeAt(count - 2);
beforeLast.next = null;
tail = beforeLast;
count--;
}
// видалення елемента за позицією
public void del(int position) {
if (count == 0) {
return;
}
if (position <= 0) {
delHead();
return;
}
if (position >= count) {
delTail();
return;
}
Node beforeDel = getNodeAt(position - 1);
beforeDel.next = beforeDel.next.next;
count--;
if (position == count) {
tail = beforeDel;
}
}
// очищення списку
public void clear() {
head = null;
tail = null;
count = 0;
}
// виведення списку
public void print() {
if (count == 0) {
System.out.println("Список порожній!");
return;
}
Node current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
// повернення кількості елементів
public int getCount() {
return count;
}
// перевірка, чи список порожній
public boolean isEmpty() {
return count == 0;
}
// пошук першого входження елемента
public int indexOf(int data) {
Node temp = head;
int i = 0;
while (temp != null) {
if (temp.data == data) {
return i;
}
temp = temp.next;
i++;
}
return -1;
}
// перевірка, чи містить список елемент
public boolean contains(int value) {
return indexOf(value) != -1;
}
// отримання значення за індексом
public int get(int index) {
if (index < 0 || index >= count) {
throw new IndexOutOfBoundsException("Недійсний індекс: " + index);
}
return getNodeAt(index).data;
}
// зміна значення за індексом
public void set(int index, int value) {
if (index < 0 || index >= count) {
throw new IndexOutOfBoundsException("Недійсний індекс: " + index);
}
getNodeAt(index).data = value;
}
// розворот списку
public void reverse() {
if (count <= 1) {
return;
}
Node prev = null;
Node current = head;
tail = head;
while (current != null) {
Node next = current.next;
current.next = prev;
prev = current;
current = next;
}
head = prev;
}
// повернення масиву елементів
public int[] toArray() {
int[] result = new int[count];
Node current = head;
for (int i = 0; i < count; i++) {
result[i] = current.data;
current = current.next;
}
return result;
}
// допоміжний метод для отримання вузла за індексом
private Node getNodeAt(int index) {
if (index < 0 || index >= count) {
throw new IndexOutOfBoundsException("Недійсний індекс: " + index);
}
Node current = head;
for (int i = 0; i < index; i++) {
current = current.next;
}
return current;
}
}
class Program {
public static void main(String[] args) {
SinglyLinkedList sll = new SinglyLinkedList();
// вставка в кінець списку
sll.addTail(10);
sll.addTail(20);
sll.addTail(30);
sll.addTail(40);
System.out.println("Після додавання в кінець:");
sll.print();
// вставка на початок списку
sll.addHead(50);
sll.addHead(60);
sll.addHead(70);
sll.addHead(80);
System.out.println("Після додавання на початок:");
sll.print();
// кількість елементів, пошук елементів
System.out.println("Кількість: " + sll.getCount());
System.out.println("Індекс 70: " + sll.indexOf(70) + ", Індекс 90: " + sll.indexOf(90));
System.out.println("Чи містить 20? " + sll.contains(20));
// вставка за позицією
sll.insert(-1, -1);
System.out.println("Вставка за позицією -1:");
sll.print();
sll.insert(2, 2);
System.out.println("Вставка за позицією 2:");
sll.print();
sll.insert(22, 22);
System.out.println("Вставка за позицією 22:");
sll.print();
// зміна елемента за індексом
sll.set(1, 100);
System.out.println("Після заміни елемента за індексом 1:");
sll.print();
// отримання елемента за індексом
System.out.println("Елемент за індексом 1: " + sll.get(1));
// видалення з початку списку
sll.delHead();
sll.delHead();
System.out.println("Після видалення двох елементів з початку:");
sll.print();
// видалення з кінця списку
sll.delTail();
System.out.println("Після видалення з кінця:");
sll.print();
// видалення за індексом
sll.del(1);
System.out.println("Після видалення за індексом 1:");
sll.print();
// розворот списку
sll.reverse();
System.out.println("Після розвороту списку:");
sll.print();
// очищення списку
sll.clear();
System.out.println("Після очищення:");
sll.print();
System.out.println("Чи порожній? " + sll.isEmpty());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment