java中如何在LinkedList尋找元素

來源:互聯網
上載者:User

LinkedList類是雙向列表,列表中的每個節點都包含了對前一個和後一個元素的引用.

LinkedList的建構函式如下

1. public LinkedList():  ——產生空的鏈表
2. public LinkedList(Collection col):  複製建構函式

我們可以使用LinkedList的indexOf()或者lastIndexOf()方法來尋找元素(遇到第一個匹配的元素即停止搜尋,同時返回該元素的索引。所以,當LinkedList中有兩個同樣的元素的時候,使用這兩個方法只會返回第一個匹配的元素)。雖然LinkedList不像ArrayList一樣支援隨機搜尋(random search),但是我們仍可以遍曆整個線性表,尋找需要的元素。

java.util.LinkedList是雙向鏈表的實現,因此有兩個可以用來進行尋找操作,分別是:

indexOf()表示從線性表的頭部開始搜尋,當找到第一個匹配的元素後就停止搜尋並返回匹配的元素的索引
lastIndexOf()表示從線性表的尾部開始搜尋,當找到第一個匹配的元素後就停止搜尋並返回匹配的元素的索引。
它們的索引值都是以頭部為起點開始計算的,所以對於LinkedList中同一個的元素,使用indexOf()和lastIndexOf()兩個方法返回的值是一樣的。如果LinkedList中有兩個一樣的元素,則使用lastIndexOf()和indexOf()返回的結果肯定是不同的。正如前面所說的,LinkedList並不支援隨機搜尋,要搜尋一個元素需要遍曆整個List,這意味這尋找的時間複雜度(time complexity)是O(n)。

 

下面是LinkedList的結構描述:

linked+list+daa+structure+in+Java

代碼執行個體:

import java.util.LinkedList;
 
/**
 * Java Program to search an element inside LinkedList.
 * LinkedList doesn't provide random search and
 * time complexity of searching is O(n)
 *
 * @author java67
 */
 
public class LinkedListSearch {
 
    public static void main(String args[]) {
 
       LinkedList<Integer> ints = new LinkedList<>();
        ints.add(1001);
        ints.add(1002);
        ints.add(1003);
        ints.add(1004);
        ints.add(1005);
        ints.add(1003);
       
       
        // let's search a duplicate element in linked list
        // for duplicate elements indexOf() and lastIndexOf() will
        // return different indexes.
        System.out.println("First index of 1003 is : " + ints.indexOf(1003));
        System.out.println("Last index of 1003 is : " + ints.lastIndexOf(1003));
       
 
        // let's search an element which is not appeared twice
        // for unique elements both indexOf() and lastIndexOf() will return
        // same position
        System.out.println("First index of 1002 is : " + ints.indexOf(1002));
        System.out.println("Last index of 1002 is : " + ints.lastIndexOf(1002));
 
    }
 
}
 
Output :
First index of 1003 is : 2
Last index of 1003 is : 5
First index of 1002 is : 1
Last index of 1002 is : 1

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.