Java data structures and algorithms-List of links

Source: Internet
Author: User
Tags class definition


Q: Why should I introduce the concept of a linked list? What is it that solves the problem?


A: the array as a data storage structure has a certain flaw, in the unordered array, the search is inefficient, and in an ordered array, the insertion efficiency is very low, no matter in which array the deletion efficiency is very low, and after an array is created, its size is immutable.



A: in this article, we will learn a new data structure-linked list, which can solve some of the above problems, the linked list is probably the second most widely used storage structure following the array.


Q: Node?


A: in the list, each data item is included in the "node", you can use node, or entry and other nouns to represent the node, this article uses entry to represent. Each Entry object contains a field referenced to the next node (usually called next), and the structure of each node in the single-linked list is as follows:

The class definition for defining a single-linked table node is as follows:


 
 
class Entry<E> {
    E mElement;
    Entry<E> mNext;

    public Entry(E element, Entry<E> next) {
        mElement = element;
        mNext = next;
    }
}
Q: Single linked list?


A: the node that makes up the list has only one pointer field that points to the successor node.


Q: The Java implementation of single-link list?


A: Example: Singlelinkedlist.java



A: The LinkedList class contains only one data item mheader, called a table header: That is, a reference to the first node in the linked list. It is the only linked list that needs to be maintained for permanent information to locate all other link points. From Mheader, you can find other nodes along the list through the Mnext field of each node.



A: AddFirst () method--The function is to insert a new node in the table header.






A: the Removefirst () method--is the inverse of the AddFirst () method, which disconnects the first node by re-pointing the Mheader to the second node.

In C + +, when you remove a node from a linked list, you need to consider how to release the node. It's still somewhere in memory, but now there's no pointer to it, how will it handle it? In Java, garbage collection (GC) will destroy it at some point in the future, and now this is not a job for programmers to worry about.
Note that the Removefirst () method assumes that the list is not empty, so before calling it, you should first call the empty () method to verify this.


Q: How do I find and delete a specified node?


A: indexOf (Object) Method-Returns the index of the specified element that first appears in this list, or 1 if the element is not included in this list.



Get (int) Method--Returns the element at the specified position in this list.



A: Remove (Object)-Removes the first occurrence of the specified element (if present) from this list.
Search for the node you want to delete first, and if you find it, you must link the previous node to the next one. The only way to know the previous node is to have a reference to it previous (the previous variable is assigned a value of current whenever the current variable is assigned to Current.next).



A: Example: Singlelinkedlist.java


Q: Double-ended linked list?


A: The double-ended list (double-ended list) is based on the top of the single linked list with a footer, that is, a reference to the last node. Such as:



A: a reference to the last node allows a node to be inserted directly at the end of the table like a header. Of course, you can still insert a node at the end of a regular single-linked list by traversing the entire list until it reaches the end of the table, but this method is inefficient.


Q: The Java implementation of the double-ended linked list?


A: Example: Doubleendedlist.java



A: Doubleendedlist has two items, header and tailer, one pointing to the first node in the list, and the other pointing to the last node.



A: If there is only one node in the list, the header and last point to it. If there are no nodes, two are null values.



A: If the list has only one node, tailer must be assigned null when it is deleted.



A: addlast () Method--Inserts a new node at the end of the table.


Q: What is the efficiency of a linked list?


A: at the table header insertion and deletion is very fast, only need to change one or two reference values, so the time spent O (1).



A: finding, deleting, and inserting in front of a specified node requires searching for half of the nodes in the list, requiring an O (n) comparison, and an O (n) comparison to perform these operations in the array. But the list is still a bit faster because the list doesn't need to move anything when inserting and deleting nodes.



A : there is another advantage to a linked list than an array is how much memory the list needs to use, unlike when the array is fixed at the time it was created.



A: a vector is an extensible array that can solve this problem with variable lengths, but it often allows only fixed increments (such as an increase of 1 time times the array capacity when the overflow is imminent). This solution is still less efficient in terms of memory usage than linked lists.


Q: The stack implemented with a linked list?


A: Example: Stack.java



A: the user of the stack does not need to know whether the stack is using a linked list or an array implementation. Therefore, the test cases for the stack class are not separate on these two.


Q: What is the queue implemented with a linked list?


A: Example: Queue.java



A: shows a queue implemented with a double-ended list.


Q: When should I use a linked list instead of an array to implement stacks and queues?


A: This depends on whether you can accurately predict the amount of data the stack or queue needs to hold. If this is not very clear, the list is more suitable than the array. Both are fast, so speed may not be the focus of consideration.


Q: What is an abstract data type (ADT)?


A: In a nutshell, it's a way of thinking about data structures: Focus on what it does, and ignore what it does.



A: stacks and queues are examples of ADT, and we have seen stacks and queues either as arrays or linked lists, and for users who use them without knowing the specifics of the implementation (the user does not know how the method works or how the data is stored).



A: The concept of ADT is important in the software design process, and if you need to store data, start thinking about it in its actual operation, such as accessing the last inserted data item? Or the first one? Is the item of a specific value? Or an item in a specific location? Answering these questions leads to the definition of ADT.



A: The details should be considered only after the full definition of ADT.



A: by removing the implementation details from the ADT specification, you can simplify the design process and make it easy to modify at some point in the future. If the user only touches the ADT interface, it should be possible to modify the implementation of the interface without "interfering" with the user code.



A: of course, once ADT is designed, the internal data structure must be carefully selected to make the prescribed operation as efficient as possible. For example, random access to element A, then the list is not good enough, because the list is not an efficient operation, the choice of data will be better effect.


Q: Ordered linked list?


A: in an ordered list, data is ordered in order of key values, and the deletion of an ordered list is often limited to the deletion of the smallest (or largest) node in the table header.



A: in general, an ordered list can be used in most cases where an ordered array is required. The advantage of an ordered list is the speed of the insertion, because the element does not need to be moved, and the list can expand the required memory at any time, and the array can only be confined to a fixed size of memory.



A: Example: Sortedlinkedlist.java



A: When the algorithm finds the location to be inserted, the data item is inserted in the usual way: point the next field of the new node to the next node, and then point to the new node the next field of the previous junction. However, special cases need to be considered: nodes may be inserted in the header, or at the end of the table.


Q: What is the efficiency of an ordered list?


A: an O (N) comparison (average N/2) is required to insert or delete an item in an ordered list, because the correct position must be found in the chain of steps. However, the minimum value can be found or removed in the time of O (1) because it is always in the table header.



A: If an application accesses the smallest item frequently and does not need to be inserted quickly, the ordered list is an effective option, for example, the priority queue can be implemented with an ordered list.


Q: List insertion Sort (lists insertion sort)?


A: ordered lists can be used in an efficient sorting mechanism. Suppose there is an unordered array, if you take the data from this array and then insert the ordered list one by one, they are arranged automatically in order. Then they are removed from the ordered list and re-placed into the array, then the array is sorted.



A: in essence, the array-based insertion sort is the same as the number of O (N2) comparisons, just that half of the existing data on the array will involve movement, which is equivalent to the N2/4 movement, by comparison, the list needs only 2 * N moves: Once from the array to the linked list, One is from a linked list to an array.



A: But there is a drawback to the list insertion: it is about twice times more space.



A: Example: Linkedlistsort.java


Q: Doubly linked list?


A: A doubly linked list provides the ability to traverse forward and to traverse the entire list backwards, where the secret is that there are two pointers in each of its data nodes, pointing directly to successive and direct precursors respectively.



A: A doubly linked list does not have to be a double-ended list (keeping a reference to the last element of the list), but this is useful. So the following example will contain the properties of the double end.


Q: The Java implementation of doubly linked list based on two-way list?


A: Example: Doublylinkedlist.java



A: addfirst (E) method: Inserts the specified element at the beginning of this list.



A: addlast (E) Method: Adds the specified element to the end of this list.



A: Add (Index, E) method: Inserts the specified element in the location specified in this list.



A: remove (Object o) method: Removes the first occurrence of the specified element (if present) from this list.


Q: Double-ended queue based on doubly linked list?


A: A doubly linked list can be used as the basis for a double-ended queue. In a double-ended queue, you can insert and delete from any end, and a doubly linked list provides this capability.


Q: Why should I introduce the concept of iterators?


A: An array is maintained at the bottom of the ArrayList, LinkedList is a linked list structure, and HashSet relies on a hash table, each of which has its own unique data structure. Because the internal structure of the container is different, many times you may not know how to traverse the elements in a container. So in order to make it easier to manipulate elements inside the container, Java introduces iterators.



A: Extract the access logic from different types of collection classes to avoid exposing the internal structure of the collection externally.
For arrays we use subscripts for processing:


(0array.  LengthiSystem.  Out.  println(array[i]);}            


For linked lists, we start with the table header:


 
public void displayForward() {
        System.out.print("List (first-->last): [");
        Entry<E> current = mHeader;
        while(current != null) {
            E e = current.mElement;
            System.out.print(e);
            if (current.mNext != null) {
                System.out.print(" ");
            }
            current = current.mNext;
        }
        System.out.print("]\n");
    }


A: different sets will correspond to different traversal methods, and the client code cannot be reused. How to integrate the above two sets in practical applications is rather cumbersome. So there is iterator, which always uses the same logic to iterate over the collection. So that the client itself does not need to maintain the internal structure of the collection, all internal state is maintained by iterator. Instead of dealing directly with the collection, the client controls the iterator to send it forward-backward instructions and can traverse the collection.



A: The iterator pattern provides a way to access individual elements in a container object without exposing the inner details of the object container.


Q: What is an iterator-defined interface?


A: The iterator contains a reference to the data item in the structure and is used to iterate over the structure of the object. The following is an interface definition for an iterator:


 
 
public interface Iterator<E> {
    boolean hasNext();

    E next(); 

    void remove();
}
public interface ListIterator<E> extends Iterator<E> {
    boolean hasPrevious(); 

    E previous();

    int nextIndex();

    int previousIndex();

    void set(E e);
}


A: the iterator () method of each container returns a standard iterator implementation. In general, the connections between iterators and lists in Java are implemented by setting iterators to the inner class of the linked list, and C + + as "friend".



A: as shown in the two iterators that point to a node in the list:





q:jdk1.6 's LinkedList iterator?


A: The Iterator class Listitr implements the Listiterator interface, which is defined as follows:


Listiterator<E{}   


A: Example: Listiteratortestcase.java





Q: Where does the iterator point?


A : One design problem for an iterator class is to decide where the iterator should point after a different operation. While the Add () implementation in Linkedlist.listitr in JDK1.6, the next pointer always points to the table header, which assumes that the call is iterator () and does not specify a subscript.


Q: Summary of this article
    • A list contains a LinkedList object and many entry objects.
    • Next field null means the end of the linked list.
    • Inserting nodes at the table header requires that the next field of the new node point to the original first node, and then point the header to the new node.
    • To delete a node in the header, point the header to Header.next.
    • To traverse the list, start with the header, and then from one node to the next, find the next node with the next field of each node.
    • By traversing a linked list, you can find a node that has a specific value, and once found, you can display, delete, or otherwise manipulate the node.
    • The new node can be inserted in front of or behind a node of a particular value, first to traverse to find the node.
    • The double-ended list maintains a reference to the last node in the list, which is usually the same as the header, called Tailer.
    • Double-ended lists allow data items to be inserted at the end of a table.
    • An abstract data type is a data storage class that does not involve its implementation.
    • Stacks and queues are ADT, which can be implemented either in arrays or in linked lists.
    • In an ordered list, nodes are sorted in ascending or descending order of keywords.
    • It is necessary to insert an O (N) time in the ordered list because the correct insertion point must be found, and the deletion of the minimum node requires O (1) time.
    • In a doubly linked list, each node contains a reference to the previous node, along with a reference to the latter node.
    • A doubly linked list allows for reverse traversal and can be removed from the end of the table.
    • An iterator is a reference that is encapsulated in a class object, which points to a node in the associated list.
    • The iterator method allows the consumer to move an iterator along a linked list and access the currently pointed node.
    • You can use iterators to traverse linked lists and perform certain operations on selected nodes.


Java data structures and algorithms-List of links


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.