[Java Basics] Detailed explanation of Java LinkedList: a flexible partner for data structures

Insert image description here

In Java programming, data structures play a vital role. These data structures can help us organize and manage data, making our code more efficient and maintainable. One of them is that LinkedListit is a flexible data structure that allows us to perform insertion and deletion operations efficiently. This blog will delve into Java LinkedList, from basic concepts to advanced usage, and present you with comprehensive information.

1. What is LinkedList?

LinkedListIt is a doubly linked list data structure in Java. It consists of a sequence of nodes, each containing data elements and references to the previous and next nodes. This structure makes LinkedListinsertion and deletion operations very efficient because it does not require reallocation of memory space like arrays.

2. Create and initialize LinkedList

In Java, you can create and initialize using LinkedList:

LinkedList<String> linkedList = new LinkedList<>();

This creates an empty LinkedListobject to store the string elements. You can also initialize using an existing collection LinkedList, for example:

List<String> stringList = new ArrayList<>();
stringList.add("苹果");
stringList.add("香蕉");

LinkedList<String> linkedList = new LinkedList<>(stringList);

This will create an element containing "apple" and "banana" LinkedList.

3. Basic operations

3.1 Add elements

3.1.1 addMethod

To LinkedListadd elements to a , you can use addthe method. It adds elements to the end of the list.

linkedList.add("橙子");

3.1.2 Add element at specified position

You can also use addthe method to insert an element at a specified position. The specified position is determined by index, starting from 0.

linkedList.add(1, "葡萄"); // 在索引 1 处插入 "葡萄"

3.2 Get elements

3.2.1 getMethod

To get LinkedListan element in , you can use getthe method, specifying the index of the element.

String fruit = linkedList.get(0); // 获取第一个元素

3.3 Delete elements

3.3.1 removeMethod

To remove LinkedListelements from , you can use removethe method. You can specify the element to be removed or the index of the element to be removed.

linkedList.remove("香蕉"); // 删除 "香蕉"
linkedList.remove(1); // 删除索引 1 处的元素

4. Traverse LinkedList

Traversing LinkedListcan be done in different ways, the most common are using for-eachloops or iterators.

4.1 Using for-eachloops

for (String fruit : linkedList) {
    
    
    System.out.println(fruit);
}

4.2 Using iterators

Iterator<String> iterator = linkedList.iterator();
while (iterator.hasNext()) {
    
    
    String fruit = iterator.next();
    System.out.println(fruit);
}

5. Special operations

5.1 Add elements at the beginning and end

LinkedListAllows efficient addition of elements at the beginning and end.

5.1.1 Adding elements at the beginning

linkedList.addFirst("草莓");

5.1.2 Adding elements at the end

linkedList.addLast("樱桃");

5.2 Insert elements at specific positions

LinkedListAlso allows inserting elements at specific positions.

linkedList.add(2, "葡萄"); // 在索引 2 处插入 "葡萄"

5.3 Replace elements

You can use setthe method to replace LinkedListelements in .

linkedList.set(1, "蓝莓"); // 将索引 1 处的元素替换为 "蓝莓"

6. Performance considerations

6.1 Comparison with ArrayList

There is a performance trade-off when considering using LinkedList. Compared to ArrayList, LinkedListit is generally faster in insertion and deletion operations because it does not require moving a large number of elements. However, it has poor performance when accessing elements randomly because the linked list needs to be traversed starting from the head or tail.

6.2 Time complexity

  • Adding and removing elements: average time complexity is O(1) (when the position is known), worst case O(n) (if the entire linked list needs to be traversed).
  • Get elements: The average time complexity is O(n/2) (in the average case, half of the linked list needs to be traversed).
  • Random access to elements: O(n) in the worst case (needs to traverse the entire linked list from the beginning or the end).

7. Precautions for use

When using LinkedList, you need to pay attention to the following matters:

  • LinkedListNot thread safe. If used in multiple threads, appropriate synchronization measures must be taken or thread-safe alternatives considered.
  • Avoid excessive random access as it has poor performance. Consider using if frequent random access is required ArrayList.
  • Use large with caution LinkedListas it can take up a lot of memory.

8. Advanced usage

8.1 Doubly linked list

LinkedListis an implementation of a doubly linked list, which means that each node contains a reference to the previous node and the next node. This bidirectional connection makes traversing both forward and backward through the linked list very efficient. Here are some advanced usage examples of doubly linked lists:

8.1.1 Traverse the linked list in reverse order

LinkedListThe bidirectional nature of makes reverse order traversal easy. You can start traversing from the end of the linked list and keep following the reference of the previous node until you reach the head of the linked list.

LinkedList<String> linkedList = new LinkedList<>();
// 添加元素到链表
// ...
// 逆序遍历链表
ListIterator<String> iterator = linkedList.listIterator(linkedList.size());
while (iterator.hasPrevious()) {
    
    
    String item = iterator.previous();
    System.out.println(item);
}

8.1.2 Inserting elements at specific positions

The property of a doubly linked list makes inserting an element at a specific location more efficient because you can traverse in both directions. This can provide performance benefits when an element needs to be inserted in the middle of a linked list.

LinkedList<String> linkedList = new LinkedList<>();
// 添加元素到链表
// ...
// 在中间位置插入元素
ListIterator<String> iterator = linkedList.listIterator(linkedList.size() / 2); // 在中间位置开始
iterator.add("新元素");

8.2 Circular linked list

LinkedListIt can also be used as a circular linked list, that is, the last node of the linked list points to the first node, forming a closed loop. This structure is very useful in certain algorithms and data structures, such as circular queues.

LinkedList<String> circularList = new LinkedList<>();
circularList.add("元素1");
circularList.add("元素2");
circularList.add("元素3");

// 构建循环链表,将最后一个元素指向第一个元素
circularList.getLast().setNext(circularList.getFirst());

// 遍历循环链表
Node<String> currentNode = circularList.getFirst();
do {
    
    
    System.out.println(currentNode.getData());
    currentNode = currentNode.getNext();
} while (currentNode != circularList.getFirst());

8.3 Linked lists as queues and stacks

LinkedListCan be used as queue and stack implementations. It supports first-in-first-out (FIFO) operations for queues and last-in-first-out (LIFO) operations for stacks. Here is LinkedListan example of how to implement queues and stacks using :

8.3.1 Implement queue using linked list

LinkedList<String> queue = new LinkedList<>();
// 入队
queue.offer("元素1");
queue.offer("元素2");
// 出队
String item = queue.poll();

8.3.2 Implement stack using linked list

LinkedList<String> stack = new LinkedList<>();
// 入栈
stack.push("元素1");
stack.push("元素2");
// 出栈
String item = stack.pop();

These advanced uses demonstrate LinkedListflexibility and functionality in a variety of scenarios. Depending on your needs, you can make full use of its doubly linked list features to solve the problem.

9. Sample code

Here is some LinkedListsample code using :

// 创建一个 LinkedList
LinkedList<String> linkedList = new LinkedList<>();

// 添加元素
linkedList.add("苹果");
linkedList.add("香蕉");

// 获取元素
String fruit = linkedList.get(0);

// 删除元素
linkedList.remove("香蕉");

// 遍历 LinkedList
for (String item : linkedList) {
    
    
    System.out.println(item);
}

10. Summary

LinkedListIt is a powerful data structure in Java that is very efficient in insertion and deletion operations. However, performance is poor when accessing elements randomly, so use them carefully. I hope this blog can help you better understand and use it LinkedList, and make wise choices when writing Java code. Whether you're a beginner or an experienced developer, mastering LinkedListwill add new tools and techniques to your programming journey.

Guess you like

Origin blog.csdn.net/qq_21484461/article/details/132796028