The realization of single-linked list-java

Source: Internet
Author: User
Tags garbage collection

This content is reproduced, the original address: data structure (a) The realization of single-linked list-java

Data structure is still very important, even if it is not the kind of very good, but at least to know the basics of things, this series even to review the data structure previously learned and fill their knowledge in this piece of the vacancy. Come on. Cherish the time of free study in the campus. The course of studying data structures in the order of list , stack, queue, sort, array, tree, and so on.

-wh

The concept of a single linked list

A linked list is the most basic data structure, which stores your schematic diagram as shown in

          

Shown above is a single-linked storage schematic diagram, simple and easy to understand, head for the first node, he does not store any data, but to act as a pointer to the list of real data in the first node, and each node has a next reference, point to the next node, a section to the following record, Until the last node, where next points to null.

There are many kinds of linked lists, such as single linked list, double linked list, and so on. We learn the single-linked list, the others understand the principle is actually the same.

Second, using Java to implement a single-linked list

Language is just a tool, the structure of the real experience is that kind of thought, this sentence is true, no matter what to write, its thinking is unchanged. The previous use of C + +, now using Java, Step-by-step implementation.

2.1. Write a node class to act as a node model. We know that there are two properties, 1 of the data,2 storing the data, and the next node's reference,

          

 Packagecom.wuhao.demo01; Public classNode {//for convenience, both variables use public, without the need to write a get, set method for private. //variables for storing data, simple point, int type directly     Public intdata; //The variable that holds the node, the default is null .     PublicNode Next; //constructs a value that can be assigned to data at construction time     PublicNode (intdata) {         This. data =data; }}
View Code

2.2. Simple operation of single linked list (add, delete, get total length, list element sort, List traversal)

            

2.2.1, add node operation, AddNode (node)

             

Idea: In the beginning, I would have thought if there were any knots. is not necessary to determine the insertion is the first node of the problem, but after the completion of the discovery is not necessary, is not the first node operation is the same, so by moving the pointer to traverse the entire list, find the last node, add later. No difficulty.

    /*** Add action * directly at the end of the list to insert the new node can be * The original last node of the next point to the new node*/     Public voidAddNode (node node) {//there are nodes in the list, and the last node is traversed .Node temp = head;//a moving pointer (the head node is a pointer to a node)         while(Temp.next! =NULL){//iterate through the single-linked list until the last one jumps out of the loop. temp = Temp.next;//Move backward one node, pointing to the next node. } temp.next= node;//temp is the last node or the head node, and the next point points to the new node.}
View Code

2.2.2, inserts a node to the specified position in the list. Insertnodebyindex (int index,node Node)

              

Note: To know what the prerequisites are for the insert operation, you can write the code, and then consider if inserting it in a special position is the same. There is also the need to make the insertion position is feasible judgment.

    /*** Insertnodebyindex: Inserts the node at the specified position in the list. * Insert operation needs to know 1 nodes, the previous node of the current position * Index: The position of the inserted list, starting from 1 * node: inserted node*/     Public voidInsertnodebyindex (intIndex,node Node) {        //first you need to determine whether the specified location is legal,        if(index<1| | Index>length (+1)) {System.out.println ("The insertion position is not valid. "); return; }        intlength = 1;//Record we traverse to the first node, which is the record position. Node temp = head;//a movable pointer         while(Head.next! =NULL){//traversing a single linked list            if(index = = length++) {//determines whether the specified location is reached. //Note that our temp represents the previous node in the current position. //a node after the previous node's current position .//temp Temp.next temp.next.next//The insert operation. Node.next =Temp.next; Temp.next=node; return; } temp=Temp.next; }    }
View Code

2.2.3, delete node delnodebyindex (int index) at the specified location

              

    /*** Delete the node at the specified location by index, which is the same as adding the node at the specified position, and find the exact position first.     The delete operation is then performed.     * The delete operation needs to know 1 nodes: and the previous node of the current position. * @paramIndex: The position in the list, starting from 1 **/     Public voidDelnodebyindex (intindex) {        //determine if index is reasonable        if(Index<1 | | index>Length ()) {System.out.println ("Reasonable location"); return; }        //the steps are the same as Insertnodebyindex, except that the operation is not the same.         intLength=1; Node Temp=Head;  while(Temp.next! =NULL){            if(Index = = length++){                //The delete operation. Temp.next =Temp.next.next; return; } temp=Temp.next; }        }
View Code

2.2.4, single-linked list to select Sort Selectsortnode ()

The premise is to know what sort of selection is, and if not, check out the article I'm explaining sort of

              

Analysis

              

    /*** Sort the nodes in the list, using the selection sort in order from small to large. * Use double traversal.     The first-level traversal, the normal traversal of the list, the second traversal, the traversal of the first layer of the node used by the node behind all the nodes and compare with it * Select the sort is relatively simple, understand its principle, can write out. */     Public voidSelectsortnode () {//Judging the list length is more than 2, otherwise there is only one element, it is not sorted.         if(Length () <2) {System.out.println ("No sorting Required"); return; }        //Select SortNode temp = head;//The first-level traversal uses the move pointer, which points to the head node most, and the first node is represented by a temp.next .         while(Temp.next! =NULL){//the first layer iterates through the linked list, starting at the first node.Node secondtemp = Temp.next;//the second-level traversal uses the move pointer, Secondtemp points to the first node, we need to use the second node to start, so with Secondnode.next             while(Secondtemp.next! =NULL){//second-level traversal, starting with the second node.                if(Temp.next.data > SecondTemp.next.data) {//all nodes in the second layer are compared in turn with the nodes selected in the first traversal,                    intt =SecondTemp.next.data; SecondTemp.next.data=Temp.next.data; Temp.next.data=T; } secondtemp=Secondtemp.next; } temp=Temp.next; }            }
View Code

2.2.5, single-linked list for insertion sort insertsortnode ()

Premise: To know what an insert sort is. This uses the insertion sort to write me for a long time, the same state, and I think my own writing efficiency is not very high. Anyway, it's a mule, a horse, and a sneak.

              

              

    /*** The list is inserted and sorted in order from large to small, as long as it will be written here, then the handwriting with array insertion sort * is the same. Understand the principle first.     What is the insert sort, so that the code is good to write. * Insert sort: Divided into two groups, a group as an ordered sequence, a group as unordered, the elements in the unordered group and the elements in the ordered group comparison (how to compare, then you need to know what the principle of insert sorting is not too much elaborated here) * Here I think of the method is to construct an empty list as an ordered sequence, and the original     The old linked list is unordered sequence, according to the principle, step by step encoding can be. *         */     Public voidInsertsortnode () {//Judging the list length is more than 2, otherwise there is only one element, it is not sorted.         if(Length () <2) {System.out.println ("No sorting Required"); return; }        //Create a new linked listNode Newhead =NewNode (0);//the head node of the new linked listNode newtemp = Newhead;//move pointer for new linked listNode temp = head;//move pointer for old linked list        if(Newtemp.next = =NULL){//put the first node directly into the new linked list. Node node =NewNode (Temp.next.data); Newtemp.next=node; Temp= Temp.next;//The pointer moves to the next bit (at the second node) in the old linked list.         }         while(Temp.next! =NULL){//traversing an existing linked list             while(Newtemp.next! =NULL){                //compare to the first node in the new list and add to the new linked list if the criteria are met, and note that the node is added at the first position .//if not, then compare with the second node in the new list, if not, jump out while and determine whether it is the last node in the new list, and if so, add it directly after the new list.                                if(NewTemp.next.data <temp.next.data) {Node Node=NewNode (Temp.next.data); Node.next=Newtemp.next; Newtemp.next=node;  Break; } newtemp=Newtemp.next; }            if(Newtemp.next = =NULL){//arrive at the end of the not meet, then the value is the smallest number in the new linked list, directly added to the list can be//add directly after a new linked listNode node =NewNode (Temp.next.data); Newtemp.next=node; }            //The old linked list pointer points to the next node, continuing the repetition and comparing the nodes in the new list. temp =Temp.next; //The moving pointer in the new list needs to be reset, pointing to the head node.Newtemp =Newhead; }        //starting with the new linked list, the old list waits for the garbage collection mechanism to retract it. Head =Newhead; }
View Code

    

2.2.6, of course, can also use bubble sort, merge sort, and so on, and so on, you can try, I will not write. If you don't understand these sorts, then look at the sort of articles I wrote.

2.2.7, calculating the length of a single linked list

              

    /**      * Calculate the length of a single-linked list, that is,     how many nodes @return     node number      */public      int  length () {        int length=0;         = head;          while NULL ) {            length++            ; = temp.next;        }         return length;    }
View Code

2.2.8, traverse single linked list, print data

                

 

    /**      * Traverse single linked list, print all data     *    /publicvoid  print ()        {=  Head.next;          while NULL ) {            System.out.print (temp.data+ ",");             = temp.next;        }        System.out.println ();    }
View Code

  

Iii. Summary

The basic single-linked list operation is the above, their own completely manual write, will be a single linked list of this data structure of the understanding of a great help. Of course, one of the more difficult is that the list of lists on the sort, said difficult is not difficult, as long as the principle of a few sort of understanding, and write pseudo-code, to achieve. Here are some things you can do, and I'll explain the answers in the next article.

3.1. How to remove duplicate data from a linked list

3.2. How to find the reciprocal k elements in a single linked list

3.3, how to realize the reverse of the list

3.4, how to output a single linked list from the end of the head

3.5. How to find the middle node of a single linked list

3.6, how to detect whether a linked list has a ring

3.7. How to delete a specified node without knowing the head node

3.8, how to determine whether two linked lists Intersect

The realization of single-linked list-java

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.