Data structure and algorithm Java version-stack and team __ Storage

Source: Internet
Author: User
Tags arrays data structures int size

Data structures are generally explained and implemented by C + +, so if like me did not learn C + + and learn Java is very embarrassing, but do not think that Java can not implement data structure of those commonly used tables Ah, tree and so on (do not know if there are no students think Java no pointers, So some features can't be implemented. This is wrong OH). This semester learned the data structure of this book, so I intend to use Java to implement the table, team, stack, tree. If you are interested you can continue to follow my follow-up action. My personal blog is for my blog. Stack

The stack is a very peculiar structure, because it is "advanced out", that is, a group of elements in the first entry into the last one out, as shown in the following figure:

The seemingly complex surface, in fact, is still an array to achieve, that is, the stack, in fact, is a linear table, just said that the entry and exit elements are at the bottom of the stack. Next, we will implement a simple stack with all of you.

 public class Sequencestack<t> {private object[] elementdata;   private int size;  The element in the stack is private int capacity;
        Array capacity//stack length is capacity public sequencestack (int capacity) {elementdata=new object[capacity];
    this.capacity=capacity;
    //Get the number of elements in the stack public int getlength () {return size;
        }//into stack public void push (T element) {elementdata[size]=element;
    size++;
        }//out stack public void pop () {elementdata[size-1]=null;
    size--;
    }//Determine if NULL public boolean IsEmpty () {return size==0;
        }//empty stack element public void Clear () {Arrays.fill (elementdata, NULL);
    size=0; //Rewrite the ToString method so that all elements of its output stack @Override public String toString () {StringBuilder sb=new StringBuilder ()
        ;
        for (int i=0;i<=size-1;i++) {sb=sb.append (elementdata[i]+ "");
    return sb+ ""; }
}

The above several pieces of code, a simple stack to achieve, if you want to what method, their own packaging to write out good, said before Linklist is a two-way linked list, if the view API will find it also provides Pop,peek,push and other methods, This actually means that linklist can also be used as a stack, of course, the chain stack, the implementation of the chain stack and linked to the realization of the basic, but only in and out of the element position and single linked list. Team

A queue is a linear table, like a stack, that is restricted by inserting elements at one end and deleting elements at the other end, as we usually do in line in our lives, buying things, buying a walk, and waiting in line. Therefore, it is "advanced first Out". As shown in the following illustration:

Next, the focus is on two important forms of the team:

-Sequential Queues
-loop Queue

Sequential Queues

Sequential queues: As the name suggests, is in order, lined up in a line, the front walk, behind. The bottom layer is still the base of the array, as is the circular queue. Let's go with the code.

public class sequencequene<t>{private object[] elementdata;   The underlying array is private int capacity; Team capacity private int front; Team head private int rear;
        Team tail//sequence constructors, initialization will be equal to 0 public sequencequene (int capacity) {Elementdata=new object[capacity] at the end of the team header;
        this.capacity=capacity;
        front=0;
    rear=0;
    //Determine if the queue is null public boolean IsEmpty () {return front==rear;
    //The number of elements in the team public int getlength () {return rear-front;
            //team, tail rear perform public void insert (T element) {//When team tail is larger than capacity-1, Team full if (rear>capacity-1) {
        throw new Indexoutofboundsexception ("Team full");
        } elementdata[rear]=element;
    rear++; //Out team, team head Front execute public void remove () {if (front==0) {throw new Indexoutofboundsexception ("Team Empty"
        );
        } elementdata[front]=null;
    front++; //Rewrite the ToString method so that its output queue @Override public StringToString () {StringBuilder sb=new StringBuilder ();
        for (int i=front;i<rear;i++) {sb=sb.append (elementdata[i]+ "");
    return sb+ "";
        //Empty queue, remember to set the end of team head to 0 public void clear () {Arrays.fill (elementdata, NULL);
        front=0;
    rear=0;
 }
}

In fact, compared to sequential stacks and sequential queues, we can find that they are very similar, the difference is only the deletion of the insertion method is a little different. But this way the implementation of the order of the queue is flawed, such as when the team head deleted (front=rear), the end of the team after adding full (rear=capacity-1), you will find that the team head is equal to the tail, this time can not add elements, can not delete elements, which caused the waste of the array

For the above problem, you can remove the entire queue element forward one after each deletion, that is, front is fixed, the team tail rear=rear-1, but so, if the queue is large, each move element is too much, performance will be greatly reduced. so we have another better way:

Looping Queues

The loop queue is a good solution to the above problem, and does not need to move any elements, performance has been a good upgrade, but need to pay attention to a few points: (front and rear for team head, tail, capacity array capacity)

1. Return queue length, need to understand front and rear who large, if rear large length is ****rear-front, vice versa is capacity-front+rear.
2. To determine whether the queue is empty, the element value at both Rear=ftront and rear is null.
3. When inserting deletion elements, if the rear and front reach a critical value, the next time the insert deletion is performed, rear and front need to "turn around".
4. Traversal, according to the size of front and rear traversal, if the rear large, direct traversal of a part can, if front>rear, then front-capacity and 0-rear two parts of the traversal.

The next step is to implement the specific steps:

public class Circlequene<t> {private object[] elementdata;   private int capacity; Team capacity private int front; Team head private int rear;
        Team Tail public circlequene (int capacity) {elementdata=new object[capacity];
        this.capacity=capacity;
        front=0;
    rear=0;
    //Determine if the loop queue is null public boolean IsEmpty () {return rear==front&&elementdata[rear]==null;
    //When the tail of the team is larger than the team head and the team tail is smaller than the team head two situations public int getlength () {return rear>front? rear-front:capacity-front+rear; public void Insert (T element) {if (front==rear&&elementdata[rear]!=null) {THR
        ow New Indexoutofboundsexception ("Team full");
        } elementdata[rear++]=element;
        If rear is over, start from zero if (rear>capacity-1) {rear=0; }///delete element public void Remove () {if (IsEmpty ()) {throw new Indexoutofboundsexception ("Team Empty")
        ; } elementdata[front++]=null;
        Front reached the critical value, "U-turn" if (front>capacity-1) {front=0;
        }//Empty queue public void clear () {Arrays.fill (elementdata, NULL);
        front=0;
    rear=0; //If the rear is greater than front, just traverse it directly, and vice versa @Override public string toString () {StringBuilder sb=new string
        Builder (); if (Rear>front) {for (int i=front;i<rear;i++) {sb=sb.append (elementdata[i]+)
            "); }}else{for (int i=front;i<capacity;i++) {sb=sb.append (elementdata[i]+
            " ");
            for (int i=0;i<rear;i++) {sb=sb.append (elementdata[i]+ "");
    } return sb+ "";
 }
}

By this, the loop queue is implemented, there are other types of queues, chain queues, two-way queues (linklist is also a special two-way chain queue, it should be the JDK provided by the collection class inside the most of the method, after all, this lad has nothing to do), but the implementation methods are similar to the above, It's not going to happen here.

Today is the end of the sharing, the next time into the tree structure .

Life is not only a skill, but also a poem and a distance.

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.