Container--linkedlist

Source: Internet
Author: User
Tags comparison table

First, preface

In the previous article we introduced one of the important implementations of List ArrayList, in most cases we use the code directly to ArrayList, because its advantage in random access is unmatched by other lists. In addition to ArrayList, the JDK also provides a list implementation, that is, LinkedList, which is based on a linked list, although we usually use a few, but it is inherently a full-featured two-way queue, can also be directly used as a stack to use, So there are times when it can be useful.

This article will introduce the implementation mechanism of this class.

Second, the realization principle

Similar to ArrayList, most of the methods in LinkedList are relatively simple, so we do not need to analyze each method, but focus on some of the content that embodies its implementation mechanism.

1) How is data stored?

LinkedList uses the data structure of the linked list to store, in the data structure we know that the linked list structure is different from the array, its physical storage space is discontinuous, each node represents a data object, node and node by reference Variable association, generally divided into one-way linked list and doubly linked list. The LinkedList uses a doubly linked list approach. Specifically, LinkedList is constructed by using the following fields or classes.

Size: This represents the number of arrays in the LinkedList, initially 0

First: The table header element of the list, initially null, node<e> type

Last: footer element, initial null, node<e> type

Node: The inner class used to represent the node, as defined below:

1 Private Static classNode<e> {2E item;//Elements3Node<e> Next;//successor4Node<e> prev;//precursor5 6         //sequence of three parameters, precursor, element, successor7Node (node<e> prev, E element, node<e>next) {8              This. Item =element;9              This. Next =Next;Ten              This. prev =prev; One         } A}

It can be seen that each node has precursors and successors, which creates a doubly linked list, noting that the list is not closed, that is, there is no referential relationship between first and last. Then all operations on the linked list can actually be understood to be the traversal of some nodes (or all) and the modification of the front and back references. Understand the operation of the list, it is easy to understand the LinkedList.

Unlike ArrayList, LinkedList does not need to expand when adding elements.

2) How do I implement get (index)?

For ArrayList, the time complexity of implementing get (Index) is O (1), while LinkedList requires O (n), because the linked list needs to be traversed, but because it is a doubly linked list, the implementation of a little bit of optimization, that is, the first to determine the index is in the first half, Or the second half, to determine whether to traverse from the table header or the end of the footer. The implementation is as follows:

  

1Node<e> node (intindex) {2         //assert Iselementindex (index);3 4         //determines the position of index across the entire list to determine whether to traverse from the beginning or from the tail5         if(Index < (size >> 1)) {6node<e> x =First ;7              for(inti = 0; I < index; i++)8x =X.next;9             returnx;Ten}Else { Onenode<e> x =Last ; A              for(inti = size-1; i > Index; i--) -x =X.prev; -             returnx; the         } -}

Because each element has a pointer to its front and back, it is convenient to do anything in that position, as long as you can navigate to the element in that position. So, in LinkedList for all methods that operate on index (such as add,remove,set,get, etc.), the node method is used to locate the element first, and then do the corresponding operation.

3) How to support the queue?

An important feature of LinkedList is the realization of the two-way queue interface (Deque), of course Deque inherit from the queue, so the one-way queues are also supported, but also provides a way to implement a stack, such as push, pop, so it is equivalent to the implementation of the stack function. Depending on the characteristics of the queue and stack, we can assume that they are simplified and have some design constraints on the list, so the linked list can be used directly as a queue and stack.

Of course, with ArrayList can also implement stacks and queues, but with the queue of the team, queued, stack out of the stack, into the stack, arraylist the underlying array size may continue to grow, and probably most of the space is not utilized, which requires a more ingenious implementation of the way to deal with, generally more complex.

But because the queue and the stack will only operate at the ends of the linked list, not involving the traversal of the elements, which just avoids the lack of the list, and the advantage of the list, so we generally use the linked list to achieve such a data structure.

For LinkedList, whether it's a table header or a footer operation is very simple, just to cite one example:

  

     Public BooleanOffer (e e) {returnAdd (e);//Team at the end of the queue    }     Public BooleanAdd (e e) {linklast (e);//add an element to the list at the end        return true; }    voidLinklast (e e) {Finalnode<e> L =Last ; FinalNode<e> NewNode =NewNode<> (L, E,NULL); Last=NewNode; if(L = =NULL) First=NewNode; ElseL.next=NewNode; Size++; Modcount++; }

The only thing to be aware of in the above logic is that we want to correctly associate the NewNode to the list and update the reference at the end of the table.

In addition, in the JDK definition of queue, in fact access elements are divided into multiple versions, throwing exceptions and non-throwing exceptions, sometimes it is easy to mix it unclear, here is the following:

Queue Methods Comparison Table

Method functions Exception version Non-exception version Description
Team at the end of the queue Add Offer

If the queue is full, execute add throws an exception for the capacity-constrained queue only.

and offer returns false directly

Team head out of the team Remove Poll Remove throws an exception when the queue is empty, and poll returns null
Get the tail element (no team) Element Peek Element throws an exception when the queue is empty, and peek returns null

Just as we gave an example of offer, we can see that the implementation and add are exactly the same, because LinkedList does not limit the size of the capacity, in which case the two implementations are the same.

The exception version is not difficult to remember, their initials are exactly the word (IS), and subsequent when we learn to block the queue, these methods also have a corresponding blocking version.

Iii. Summary

For the list, the key thing to remember is its definition of the list structure and its main steps for node operations, and the other is to understand how it implements the functionality of the queue.

Container--linkedlist

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.