LinkedList源码分析

向右看齐 2022-03-10 03:58 570阅读 0赞

1.有双链表组成,哪两个?first,last。

添加last链表

  1. void linkLast(E e) {
  2. final Node<E> l = last;
  3. final Node<E> newNode = new Node<>(l, e, null);
  4. last = newNode;
  5. if (l == null)
  6. first = newNode;
  7. else
  8. l.next = newNode;
  9. size++;
  10. modCount++;
  11. }

new Node<>(l, e, null);这个是重点

  1. Node(Node<E> prev, E element, Node<E> next) {
  2. this.item = element;
  3. this.next = next;
  4. this.prev = prev;
  5. }

在这里看来链表中存储着这个数的前一个数,和后一个数

add(E e)

  1. public boolean add(E e) {
  2. linkLast(e);
  3. return true;
  4. }
  5. void linkLast(E e) {
  6. final Node<E> l = last;
  7. final Node<E> newNode = new Node<>(l, e, null);
  8. last = newNode;
  9. if (l == null)
  10. first = newNode;
  11. else
  12. l.next = newNode;
  13. size++;
  14. modCount++;
  15. }

在last链表添加

push(E e)

  1. public void push(E e) {
  2. addFirst(e);
  3. }

表头添加

输出

  1. Iterator iterator=linkedList.iterator();
  2. while (iterator.hasNext()){
  3. System.out.println(iterator.next());
  4. }

!!!尽量不要在foreach方法中使用remove,add方法

remove()

  1. public E remove() {
  2. return removeFirst();
  3. }

删除头链表

demo

  1. LinkedList linkedList=new LinkedList();
  2. linkedList.add("1");
  3. linkedList.add("2");
  4. linkedList.add(3);
  5. //先进先出
  6. System.out.println(linkedList.getFirst()+" "+linkedList.getLast());
  7. Iterator iterator=linkedList.iterator();
  8. while (iterator.hasNext()){
  9. System.out.println(iterator.next());
  10. }
  11. linkedList=new LinkedList();
  12. linkedList.push("1");
  13. linkedList.push(2);
  14. linkedList.push(3);
  15. //先进后出,像栈
  16. Iterator iterator1=linkedList.iterator();
  17. while (iterator1.hasNext()){
  18. System.out.println(iterator1.next());
  19. }

输出:1 3
1
2
3
3
2
1

发表评论

表情:
评论列表 (有 0 条评论,570人围观)

还没有评论,来说两句吧...

相关阅读