Linkedlist java поиск элемента

Class LinkedList

Doubly-linked list implementation of the List and Deque interfaces. Implements all optional list operations, and permits all elements (including null ).

All of the operations perform as could be expected for a doubly-linked list. Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index.

Note that this implementation is not synchronized. If multiple threads access a linked list concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the list should be «wrapped» using the Collections.synchronizedList method. This is best done at creation time, to prevent accidental unsynchronized access to the list:

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

The iterators returned by this class’s iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the Iterator’s own remove or add methods, the iterator will throw a ConcurrentModificationException . Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

Читайте также:  Виды комментариев в php

This class is a member of the Java Collections Framework.

Источник

How to search a LinkedList in Java? Example

You can search an element inside LinkedList in Java by using indexOf() and lastIndexOf() methods. Though LinkedList doesn’t support random search like ArrayList, you can still go through the list, check each element and find out whether it’s an interesting element or not. Since java.util.LinkedList is an implementation of a doubly-linked list, these two methods are quite handy to search from either end e.g. indexOf() method starts the search from the head and returns an element’s position while lastIndexOf() starts the search from the tail. Though the position is not relative to the ends, they are always calculated from the head.

You can also use these two methods to find out duplicate elements. If an element has appeared twice in the linked list then the indexOf() and lastIndexOf() method will return different positions for that because it will be found at different positions from head and tail. For unique elements, both these methods will return the same position.

In this article, you will see examples of both indexOf() and lastIndexOf() methods to search a given element inside LinkedList. As I said before since LinkedList doesn’t support random search and searching an element requires list traversal, which means time complexity will be O(n).

Also, If you are good in Java but lacks data structure and algorithm skills, I strongly suggest reading Data Structures and Algorithm Analysis in Java by Mark A. Wiess. It’s a great book to build your foundation on data structure and algorithms using Java programming language.

Java Program to search element inside linked list

Here is our sample program to search a given node inside LinkedList in Java. We first build our linked list of numbers and insert 1003 twice to make it a duplicate number. Later we have used the indexOf() and lastIndexOf() method to search for a duplicate element like 1003 and a unique element 1002 inside the linked list.

From the result, you can see that indexOf() starts the search from the first element and that’s why it found 1003 at the 3rd position, which is index 2. On the other hand, lastIndexOf() starts the search from the last element and that’s why it found 1003 at 6th position i.e. index 5.

Here is a sample doubly linked list data structure :

How to search nodes inside LinkedList in Java

and here is our example to search duplicate and unique nodes inside LinkedList 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 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

From the output, you can also see those duplicate nodes has two different positions returned by indexOf() and lastIndexOf() method while for unique elements both methods return the same index.

Btw, If you are good in Java but lacks data structure and algorithm skills, I strongly suggest reading Data Structures and Algorithm Analysis in Java by Mark A. Wiess. It's a great book to build your foundation on data structure and algorithms using Java programming language.

That's all about how to search an element inside LinkedList in Java. Searching an element requires traversing the list from either end, for example from head to tail or tail to head, which is what indexOf() and lastIndexOf() method does. You can use any of these methods to find out the index of a given element in Java, but just remember that if the element is repeated then both methods can return different indices.

  • How to add elements at the first and last position in LinkedList in Java? [example]
  • The difference between LinkedList and ArrayList in Java? [answer]
  • Top 5 data structures from Java Collections framework? [article]
  • How to implement a linked list in Java? [solution]
  • How to find the middle node of the linked list in one pass? [solution]
  • How do you find the length of a singly linked list in Java? [solution]
  • What is the difference between a linked list and an array in Java? [answer]
  • How to find the first and last element from LinkedList in Java? [example]
  • How to check if the linked list contains a loop in Java? [solution]

Источник

Search an element in a Linked List

Learn Algorithms and become a National Programmer

Linked List is an efficient data structure to store data. You can learn about the basics of Linked List data structure in this wonderful post. In this session, we will explore the search operation in a Linked List.

As we discussed previously, any data structure that stores data has three basic operations:

  • Insertion: To insert data into the data structure
  • Deletion: To delete data from the data structure
  • Search: To search for a data in the data structure

In this leason, we will explore the search operation in a Linked List in depth.

The structure of a node in a Linked List is as follows:

Linked List Node

The structure of a node in a doubly Linked List is as follows:

Linked List Node

How to search an element in a Linked List?

To search an element in a Linked List, we need to traverse the entire Linked List and compare each node with the data to be search and continue until a match is found. We need to begin the search process from the first node as random access is not possible in a Linked List.

Pseudocode to search an element iteratively:

 1) Initialize a node pointer, current = head. 2) Do following while current is not NULL a) current->key is equal to the key being searched return true. b) current = current->next 3) Return false 

Pseudocode to search an element recursively:

 search(head, x) 1) If head is NULL, return false. 2) If head's key is same as x, return true; 2) Else return search(head->next, x) 

Why is searching in a Linked List slower than Arrays?

Considering that Linear Search is used in a Linked List and an Array, searching is always slower in a Linked List due to locality of reference. This is due to the following facts:

Linked Lists are stored randomly (scattered) in memory.

When a data from a particular memory location is required, the operating system fetches additional data from the memory locations that are adjacent to the original memory location. The key idea is that the next memory location to be fetched is likely to be fetched from a nearby location and this has the potential to reduce the memory fetch operations. This concept is known as locality of reference.

As Linked Lists are stored randomly, the next data to be fetched is in a far memory location and hence, locality of reference does not reduce the memory access operations.

As arrays are sequentially, locality of reference plays a great role in making search operations in array faster.

Is binary search possible in Linked List?

Yes, binary search is possible in a Linked List povided the data is sorted.

The problem is that random access is not possible in a Linked List. Hence, accessing the middle element in a Linked List takes liner time. Therefore, the binary search takes O(N) time complexity instead of O(log N) in case of an array.

As binary search has no performance advantage compared to linear search in case of a Linked List, linear search is preferred due to simple implementation and single traversal of the Linked List.

Pseudocode

Pseudocode of searching a node in a Linked List:

 //Checks whether the value x is present in linked list public boolean search(int x) < Node current = first; //Initialize current while (current != null) < if (current.data == x) return true; //data found current = current.next; >return false; //data not found > 

Implementations

Implementation of search operation in a Linked List is as follows:

Java

 import java.util.*; class LinkedList implements java.io.Serializable < private static class Node < E item; Nodenext; Node prev; Node(Node prev, E element, Node next) < this.item = element; this.prev = prev; this.next = next; >> transient int size = 0; transient Node first; transient Node last; // Creates an empty list public LinkedList() <> //Checks whether the value x is present in linked list public boolean search(int x) < Node current = first; //Initialize current while (current != null) < if (current.data == x) return true; //data found current = current.next; >return false; //data not found > // Return Node at index "index" O(N) time public Node node( int index) < if(index < (size >> 1)) < Nodex = first; for(int i=0;i else < Nodex = last; for(int i=size-1; i>index; --i) x = x.prev; return x; > > // Print all elements in the LinkedList public void printList() < Nodex = first; for(int i=0;i > private void LinkFirst(E e) < final Nodefront = first; final Node newNode = new Node<>(null, e, front); first = newNode; if( front == null) last = newNode; else front.prev = newNode; ++ size; > private void LinkLast(E e) < final Nodel = last; final Node newNode = new Node<>(l, e, null); last = newNode; if(l == null) first = newNode; else l.next = newNode; ++ size; > // Inserts a node before a non null node succ private void LinkBefore(E e, Node succ) < Nodebefore = succ.prev; Node newNode = new Node(before, e, succ); succ.prev = newNode; if(before == null) < first = newNode; >else < before.next = newNode; >++ size; > E unlinkFirst(Node f) < final Nodenext = f.next; first = next; final E element = f.item; f.item = null; f.next = null; if(next == null) last = null; else next.prev = null; -- size; return element; > E unlinkLast(Node l) < final E element = l.item; final NodenewLast = l.prev; l.prev = null; l.item = null; last = newLast; if(newLast == null) first = null; else newLast.next = null; -- size; return element; > E unlink(Node n) < final E element = n.item; final Nodebefore = n.prev; final Node next = n.next; if( before == null ) return unlinkFirst(n); else if(next == null) return unlinkLast(n); else < n.item = null; n.next = null; n.prev = null; before.next = next; next.prev = before; -- size; >return element; > void add(E e) < LinkLast(e); >void addAtEnd(E e) < LinkLast(e); >void addAtFront(E e) < LinkFirst(e); >> public class Test_LinkedList < public static void main() < LinkedListll = new LinkedList(); ll.add(10); ll.add(9); ll.add(10); ll.add(100); Node nn = ll.node(3); ll.unlink(nn); ll.add(11); ll.printList(); > > 

Complexity

  • Worst case time complexity: Θ(N)
  • Average case time complexity: Θ(N)
  • Best case time complexity: Θ(1)
  • Space complexity: Θ(1)

OpenGenus Tech Review Team

The official account of OpenGenus's Technical Review Team. This team review all technical articles and incorporates peer feedback. The team consist of experts in the leading domains of Computing.

Источник

Оцените статью