Что такое связанный список
1) каждый элемент в связанном списке называется узлом. 2) Это похоже на массив, каждый узел в связанном списке имеет часть данных и ссылку на следующий узел. 3) связанные списки имеют O (1) временную сложность для вставки или удаления в начале, то есть в позиции 0.
Как реализовать
-> -> -> -> В Java есть встроенный LinkedList, который вы можете импортировать из библиотеки утилит -> или вы можете реализовать свой собственный LinkedList
Встроенный список ссылок
LinkedListx = new LinkedList (); // to add elements to the list x.add("1"); // here the first element we added becomes the head x.add("2"); x.add("3"); x.add("4"); x.add("5"); x.remove("5"); // to traverse the linked list Iterator i = x.iterator(); while(i.hasNext()){ System.out.print(i.next()+"->"); }
реализация связанного списка, мой подход:
// LL stands for LinkedList public class LL { public Node head; public LL() { head = null; } public LL(int data) { head = new Node(data); } public void add(int data) { if (head != null) { head.appendToTail(data); } else { head = new Node(data); } } public void printList() { Node dummy = head; while (dummy != null) { System.out.print(dummy.data + "->"); dummy = dummy.next; } System.out.print("null"); } public void delete(int d) { Node newHead = new Node(0); newHead.next = head; Node previous = newHead; Node current = head; while (current != null) { if (current.data == d) { previous.next = current.next; } else { previous = current; } current = current.next; } head = newHead.next; } public class Node { Node next = null; int data; public Node(int data) { this.data = data; } void appendToTail(int d) { Node end = new Node(d); Node n = head; while (n.next != null) { n = n.next; } n.next = end; } } }
Попробуйте эти задачи в связанном списке, чтобы получить хорошее представление
Оригинал: “https://dev.to/karthik2265/singly-linkedlist-implementation-in-java-3ohk”