LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 153|回复: 0

LinkedList实现 - 查找操作

[复制链接]
发表于 2023-12-20 15:12:55 | 显示全部楼层 |阅读模式

查找操作

查找操作的本质是查找元素的下标:


查找第一次出现的index, 如果找不到返回-1;


  1.     /**
  2.      * Returns the index of the first occurrence of the specified element
  3.      * in this list, or -1 if this list does not contain the element.
  4.      * More formally, returns the lowest index {@code i} such that
  5.      * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
  6.      * or -1 if there is no such index.
  7.      *
  8.      * @param o element to search for
  9.      * @return the index of the first occurrence of the specified element in
  10.      *         this list, or -1 if this list does not contain the element
  11.      */
  12.     public int indexOf(Object o) {
  13.         int index = 0;
  14.         if (o == null) {
  15.             for (Node<E> x = first; x != null; x = x.next) {
  16.                 if (x.item == null)
  17.                     return index;
  18.                 index++;
  19.             }
  20.         } else {
  21.             for (Node<E> x = first; x != null; x = x.next) {
  22.                 if (o.equals(x.item))
  23.                     return index;
  24.                 index++;
  25.             }
  26.         }
  27.         return -1;
  28.     }
复制代码


查找最后一次出现的index, 如果找不到返回-1;


  1.     /**
  2.      * Returns the index of the last occurrence of the specified element
  3.      * in this list, or -1 if this list does not contain the element.
  4.      * More formally, returns the highest index {@code i} such that
  5.      * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
  6.      * or -1 if there is no such index.
  7.      *
  8.      * @param o element to search for
  9.      * @return the index of the last occurrence of the specified element in
  10.      *         this list, or -1 if this list does not contain the element
  11.      */
  12.     public int lastIndexOf(Object o) {
  13.         int index = size;
  14.         if (o == null) {
  15.             for (Node<E> x = last; x != null; x = x.prev) {
  16.                 index--;
  17.                 if (x.item == null)
  18.                     return index;
  19.             }
  20.         } else {
  21.             for (Node<E> x = last; x != null; x = x.prev) {
  22.                 index--;
  23.                 if (o.equals(x.item))
  24.                     return index;
  25.             }
  26.         }
  27.         return -1;
  28.     }
复制代码


------
原文链接:https://pdai.tech/md/java/collection/java-collection-LinkedList.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表