LinkedList

1. The structure of LinkedList

 http://images.cnitblog.com/blog/497634/201401/272345393446232.jpg

2. What is LinkedList?
  • A LinkedList is a data structure that behaves as a dynamic double_linked list.
  • LinkedList consist of a group of nodes which together represent a sequence, each node is composed of a data and two references.
  • LinkedList is not synchronized

             List list = Collections.synchronizedList(new LinkedList(...));

3. The definition of LinkedList

java.lang.Object --> java.util.AbstractCollection<E> --> java.util.AbstractList<E> --> java.util.AbstractSequentialList<E> --> java.util.LinkedList<E>

public class LinkedList<E> extends AbstractSequentialList<E>

                                                   implements List<E>, Deque<E>, Cloneable, java.io.Serializable {}

  • LinkedList extends AbstractSequentialList, it can be used
  • stack(LIFO)

              queue method      equal method

              push(e)                   addFirst(e)

              pop()                        removeFirst()

              peek()                      peekFirst()

  • queue(FIFO)

             queue method      equal method
             add(e)                     addLast(e)
             offer(e)                    offerLast(e)
             remove()                 removeFirst()
             poll()                        pollFirst()
             element()               getFirst()
             peek()                     peekFirst()

  • deque(double ended queue)
  • LinkedList implement List, Deque, Cloneable, java.io.Serializable interface.

4. property
transient int size = 0;

transient Node<E> first;

transient Node<E> last;

5. Constructor in LinkedList
LinkedList() // 0
LinkedList(Collection<? extends E> collection)

6. Basic Functions
  • linkFirst ----- unlinkFirst                            linkLast ----- unlinkLast
  • linkBefore ----- unlink
  • getFirst ----- getLast
  • removeFirst ----- removeLast ----- addFirst ----- addLast
  • contain -----> indexOf(Object)
  • add ----- (element/index, element)          addAll ----- (collection/index, collection)
  • remove ----- (object/index)
  • checkElementIndex                                    checkPositionIndex                   ----- throw exception

              isElementIndex                                           isPositionIndex          

7. Advance
  • peek ----- element(exception)
  • poll ----- remove(exception)
  • offer ----- offerFirst -----offerLast (add ----- addFirst ----- addLast)
  • peek ----- peekFirst ----- peekLast (retrieves, not remove)
  • poll ----- pollFirst ----- pollLast (retrieves, remove)
  • push ----- pop
8. LinkedList Traversal
  • for(Iterator iter = list.iterator(); iter.hasNext();)
        iter.next();
  • int size = list.size();
    for (int i=0; i<size; i++) {
        list.get(i);        
    }
  • while(list.pollFirst() != null)
        ;
  • while(list.pollLast() != null)
        ;
  • try {
        while(list.removeFirst() != null)
            ;
    } catch (NoSuchElementException e) {
    }
  • try {
        while(list.removeLast() != null)
            ;
    } catch (NoSuchElementException e) {
    }

Note:

// LinkedList的API
boolean       add(E object)
void               add(int location, E object)
boolean       addAll(Collection<? extends E> collection)
boolean       addAll(int location, Collection<? extends E> collection)
void              addFirst(E object)
void              addLast(E object)
void              clear()
Object          clone()
boolean       contains(Object object)
Iterator<E>  descendingIterator()
E             element()
E             get(int location)
E             getFirst()
E             getLast()
int           indexOf(Object object)
int           lastIndexOf(Object object)
ListIterator<E>     listIterator(int location)
boolean       offer(E o)
boolean       offerFirst(E e)
boolean       offerLast(E e)
E             peek()
E             peekFirst()
E             peekLast()
E             poll()
E             pollFirst()
E             pollLast()
E             pop()
void          push(E e)
E             remove()
E             remove(int location)
boolean       remove(Object object)
E             removeFirst()
boolean       removeFirstOccurrence(Object o)
E             removeLast()
boolean       removeLastOccurrence(Object o)
E             set(int location, E object)
int           size()
<T> T[]       toArray(T[] contents)
Object[]     toArray()

### 什么是LinkedList数据结构 LinkedList 是一种基于链表的数据结构,它在 Java 中通过 `java.util.LinkedList` 类实现。它既可以作为列表使用,也可以作为队列或双端队列使用[^1]。LinkedList 内部通过双向链表实现,这意味着每个节点包含前驱和后继指针,从而允许高效的插入和删除操作。 --- ### LinkedList 的构造方法 以下是 `LinkedList` 提供的两种主要构造方法: 1. **无参构造方法**: ```java public LinkedList() ``` 创建一个空的 `LinkedList` 实例[^1]。 2. **基于集合的构造方法**: ```java public LinkedList(Collection<? extends E> c) ``` 使用指定集合中的元素创建一个新的 `LinkedList` 实例,元素顺序与集合的迭代器返回顺序一致。 --- ### LinkedList 的常用方法 以下是一些常用的 `LinkedList` 方法及其功能: #### 基本操作 - **add(E e)**:将指定元素追加到列表末尾。 - **add(int index, E element)**:在指定位置插入元素。 - **remove(Object o)**:移除首次出现的指定元素(如果存在)。 - **remove(int index)**:移除指定位置的元素并返回该元素。 #### 访问元素 - **get(int index)**:返回指定位置的元素。 - **indexOf(Object o)**:返回首次出现的指定元素的索引,如果不存在则返回 `-1`。 #### 队列操作 - **offer(E e)**:将元素添加到列表末尾(等同于 `add`)。 - **poll()**:获取并移除列表头部的元素。 - **peek()**:获取但不移除列表头部的元素。 #### 栈操作 - **push(E e)**:将元素压入栈顶(等同于在列表头部插入元素)。 - **pop()**:从栈顶弹出元素(等同于移除列表头部的元素)。 --- ### 示例代码 以下是一个简单的 `LinkedList` 使用示例: ```java import java.util.LinkedList; public class LinkedListExample { public static void main(String[] args) { // 创建一个空的 LinkedList LinkedList<String> list = new LinkedList<>(); // 添加元素 list.add("Apple"); list.add("Banana"); list.add("Cherry"); // 插入元素到指定位置 list.add(1, "Date"); // 打印列表 System.out.println("List: " + list); // 移除元素 String removedElement = list.remove(2); System.out.println("Removed Element: " + removedElement); // 获取元素 String firstElement = list.get(0); System.out.println("First Element: " + firstElement); // 遍历列表 for (String fruit : list) { System.out.println(fruit); } } } ``` --- ### LinkedList 的优缺点 #### 优点 - **高效插入和删除**:由于内部是双向链表结构,插入和删除操作的时间复杂度为 O(1)[^3]。 - **支持多种操作**:可以作为列表、队列或栈使用[^4]。 #### 缺点 - **随机访问慢**:通过索引访问元素时,需要从头或尾遍历链表,时间复杂度为 O(n)[^3]。 --- ### 自定义实现 LinkedList 以下是一个简单的自定义 `LinkedList` 实现示例: ```java class Node<T> { T data; Node<T> next; Node(T data) { this.data = data; this.next = null; } } class MyLinkedList<T> { private Node<T> head; public MyLinkedList() { head = null; } public void add(T data) { if (head == null) { head = new Node<>(data); } else { Node<T> current = head; while (current.next != null) { current = current.next; } current.next = new Node<>(data); } } public void printList() { Node<T> current = head; while (current != null) { System.out.print(current.data + " -> "); current = current.next; } System.out.println("null"); } } public class CustomLinkedListExample { public static void main(String[] args) { MyLinkedList<Integer> list = new MyLinkedList<>(); list.add(1); list.add(2); list.add(3); list.printList(); // 输出: 1 -> 2 -> 3 -> null } } ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值