Linear table of data structure (Java description)

Source: Internet
Author: User

Basic Concepts

Data Structure : A collection of data elements that have one or more relationships with each other.

logical structure and physical structure

As for the data structure, we can describe the two dimensions of the logical structure and the physical structure.

A logical structure is a relationship between data elements in a data object and a form of organization between the data described in logical sense.

There are 4 types of logical structures:

    • Collection Structure (the data elements are represented only as collections, with no other relationship between elements)
    • linear Structure (there is a one-to-one relationship between data elements)
    • Tree (a one-to-many or many-to-one relationship between data elements)
    • graphs (Many-to-many relationships between data elements)

The physical structure is the storage form of the logical structure in the memory of the computer , divided into two kinds:

    • Sequential storage structure
    • Chained storage structure
linear table (list)

A Linear table is a finite sequence of 0 or more data elements.

Linear table is a linear structure, there is a one-to-one relationship between elements, the linear table can be implemented in both sequential and chained ways.

sequential storage structure, is to store the data elements of the linear table sequentially in a contiguous storage unit

  

a chained storage structure that stores data elements with a set of arbitrary storage units , the continuity of the physical storage unit is not required, and consists of a series of nodes, each of which stores the data and stores the address that points to the successor or the predecessor node.

sequential storage vs. chained storage
    • Sequential storage structure
      • Advantages
        • The implementation is relatively simple
        • Finds elements at a specified position efficient, time complexity is constant order O (1)
        • No additional logical relationships between storage elements (chained storage is randomly allocated due to storage space, need to store the logical relationship between elements)
      • Disadvantages
        • Need to pre-allocate storage space, if the number of data elements change large, it is difficult to determine storage capacity, and lead to wasted space
        • Frequent insertions and deletions may require large numbers of data elements to be moved frequently
    • Chained storage structure
      • Advantages
        • No need to allocate storage space in advance, the number of elements is not limited
        • For insert delete operation, it is very efficient to find the target location, only need to deal with the reference relationship between the elements, the time complexity is O (1)
      • Disadvantages
        • Achieve relatively complex
        • Less efficient, worst-case traversal of the entire table
        • Because the physical storage location is not fixed, additional storage of logical relationships between data elements is required
Chain-Store Code implementation

Single linked list

 PackageListdemo;/*** Created by Chengxiao on 2016/10/18.*/ Public classMylinkedlist {/*** Reference to head node*/    PrivateNode first; /*** Linear table size*/    Private intsize; /*** Node class*/    Private Static classnode{//data fields        Private intdata; //references to subsequent nodes        PrivateNode Next; Node (intdata) {             This. data =data; }    }    /*** Insert from head * Step: 1. The next link of the new node points to the current head node; 2. Point first to the new node * time complexity: O (1) *@paramData*/     Public voidInsertfirst (intdata) {Node NewNode=NewNode (data); Newnode.next=First ; First=NewNode; Size++; }    /*** Delete from head * Step: 1. Empty the next link of the Head Node 2. Point the first reference to the second node * time complexity is: O (1) *@return     */     Public BooleanDeletefirst () {if(IsEmpty ()) {return false; } Node Secondnode=First.next; First.next=NULL; First=Secondnode; Size--; return true; }    /*** Remove the I node * step: Traverse from the head node, take the I node * time complexity: O (n), this operation for the use of the array implementation of the sequential storage structure, only the constant order O (1) can be completed. * @paramIndex *@return     */     Public intGetintIndexthrowsException {if(!CheckIndex (Index)) {            Throw NewException ("Index is illegal! "); } Node Curr=First ;  for(inti=0;i<index;i++) {Curr=Curr.next; }        returnCurr.data; }    /*** traversing linear table * Time complexity: O (n)*/     Public voiddisplaylist () {Node Currnode=First ;  while(currnode!=NULL) {System.out.print (Currnode.data+" "); Currnode=Currnode.next;    } System.out.println (); }    /*** Whether the list is empty *@return     */     Public BooleanIsEmpty () {returnFirst = =NULL; }    /*** Index is legal *@paramIndex *@return     */    Private BooleanCheckIndex (intindex) {        returnIndex >= 0 && Index <size; }    /*** List Size *@return     */     Public intsize () {returnsize; }     Public Static  voidMain (String []args)throwsException {mylinkedlist mylinkedlist=Newmylinkedlist (); //Insert from HeadMylinkedlist.insertfirst (1); Mylinkedlist.insertfirst (2); Mylinkedlist.insertfirst (3); Mylinkedlist.insertfirst (4); //traversing elements in a linear tablemylinkedlist.displaylist (); //gets the second elementSystem.out.println (Mylinkedlist.get (2)); //Delete a node.Mylinkedlist.deletefirst ();    Mylinkedlist.displaylist (); }}

Output results

  4 3 2 1   2  3 2 1

Double-ended linked list

There are several basic operations listed in the linear table, considering that if you want to provide an operation Insertlast to insert at the end of the list, then since the single-linked list only retains the application first for the head node, it needs to iterate through its next link from the node to the beginning, and the time complexity is O (n )。 In fact, we can keep a reference to a tail node while preserving the reference of the head node. This makes it much easier to insert from the tail.

Double-ended linked list holds both the head node and the reference to the tail node.

    /**      * Reference     to head node */     private  Node first;     /**      * References     to tail nodes * /     private Node rear;

Inserting from the tail

/*** Double-ended list, insert from tail * Step: Point the next link of the current tail node to the new node * time complexity: O (1) *@paramData*/     Public voidInsertlast (intdata) {Node NewNode=NewNode (data); if(IsEmpty ()) { First=NewNode; Rear=NewNode; Size++; return; } Rear.next=NewNode; Rear=NewNode; Size++; }

You should also keep a reference to the tail node when doing other things, and don't repeat it here.

Doubly linked list

Think again, if we are to provide an operation to delete the tail node, the step is simple: in the process of deleting the tail node, it is necessary to set the next chain reference of its predecessor (that is, the second-to-last node) to NULL, but since our list is a single-linked list, a road to the black, to find the second-to-last node In this case, we can consider using a doubly linked list.

Each node of a doubly linked list contains two pointer fields, a predecessor node pointing to it, and a subsequent node pointing to it.

          

/*** Delete Tail node * Main steps: 1. Point the rear to the second-to-last node 2. Handle the reference chain of the associated node * time complexity: O (1) *@return     */     Public voidDeletelast ()throwsException {if(IsEmpty ()) {Throw NewException ("The linked list is empty"); } Node secondlast=Rear.prev; Rear.prev=NULL; Rear=Secondlast; if(Rear = =NULL) { First=NULL; }Else{Rear.next=NULL; } size--; }

Other operations in the same way, in the process need to maintain a reference to the node's precursor and subsequent nodes, delete operations, you need to pay attention to the removal of the various references to waste nodes, convenient GC.

Summarize

In this paper, some basic concepts of data structure, such as logical structure, physical structure and linear table are expounded. At the same time, the sequential storage structure and chain storage structure of linear table are introduced, the chain storage structure of linear table (single-linked list, double-end linked list, doubly linked list) is realized by using the Java language. The importance of data structure is undoubtedly, it is the cornerstone of software design, because of their own non-trained, although have been self-taught for a period of time, is not enough system, recently hoped to be able to re-systematically comb, this article when their data structure to learn the beginning of it, mutual encouragement.

  

Linear table of data structure (Java description)

Related Article

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.