About array/list/stack/queue image interpretation

Source: Internet
Author: User
Tags assert int size iterable stdin

"Stack":

I am a stack, first to introduce you to my family, my family is a very old family, a lot of family members, the outside world called our family as a data structure. We are the computer world that stores and organizes data. The data structure family is vital in the computer world, because our family function is powerful, the modern programming language and its API all have our family member's figure.

My family is a huge family. There are also several major branches in the family, such as trees, graphs, heaps, and hash lists. Each branch has different capabilities, so it is important for many people to choose the right data structure. Our family and algorithmic families are family friends, and basically all the important occasions the two families will appear together.

I called the stack, my dad called array, my mother called the list, my twin brother called the queue. Our family is the most important family in the whole family of data structures.

As you said, we have data structure the family is the computer world to store and organize information. My family is so powerful because we have to deal with various needs and provide different ways of storing data. Four of my family members can address different data access requirements, respectively.

1. array:

Speaking of my father--array, he's the patriarch of the data structure family, people say he's the foundation of a large family of data structures. Many programming languages have built-in arrays.

Array Dad is a very rich man, he has a lot of land. Whenever someone came to him to store the data, he would advance a contiguous piece of land (continuous memory), then the data that was given to him was stored sequentially in these contiguous fields, and when someone came to fetch the data, it was necessary to supply the data in which land the array was taken (the index of the array), The array can then go directly to that piece of land and get the data out to the person who needs to read the data. Not all data arrays can be stored, and fathers only help others store the same type of data.

An array data structure is a data structure consisting of a collection of elements of the same type, allocating a contiguous amount of memory for storage. The index of the element can be used to calculate the storage address of the element.

All of my family support a few basic operations: INSERT, delete, read.

Because the array dad stored the data in sequence, he saved the data in a piece of land that was connected. So, his feature is that addressing read data is easier, but inserting and deleting it is more difficult. This is actually relatively good understanding. The easy reason to read is that as soon as you tell the array which land you want to read from, he will go straight to the land and get the data out to you. Insertions and deletions are cumbersome, mainly because the space for these storage data is connected, for example, the numbers for 0-1-2-3-4 five plots of land are stored, but now you have to insert a piece of data into 1, which means that starting from 1, all the data in the back of the land is moved backward. It's a lot of work.

2. Linked list:

They say that men and women work together and not tired. Since the array dad has easy addressing, inserting and deleting difficult questions, he was looking for his wife to find a complementary girl--linked list. The link list Mom's feature just is addressing difficult, inserting and removing easily.

In the case of helping others to store data, the way the list is linked and the array is very different. An array is a large contiguous piece of land that is used to store data in advance. But the list doesn't do that because the list mom's home is not as rich as the array dad's home. His data store is not continuous, and the reason for this is that the mother stores the data in the land of two areas, a piece to save data, a piece to record the next data stored in which piece of land (pointer). In this way, when someone is looking for him to store data, she must first find the next piece of free land, and then keep the data inside. The way data is stored in a linked list can be used in some pieces of space.

3. Stacks and queues:

Stack, that is, me, a handsome data structure. I and the queue are a bunch of twin brothers. All two of us can be implemented using arrays and lists. Although the twins, but the two of us are a character, we ask others to store data and the order of data to be taken in accordance with our rules.

My principle is: Advanced out (Stack)

Brother's principle is: Advanced first out (queue)

I'll give you an example and you'll see that my brother and I each have a pipe to help you keep the data, of course, this tube may be an array. Dad is implemented or linked to MOM. We hold the ends of the pipe, and my pipe can only be placed in the left side of the pipe, and can only be removed from the left side of the hole. The right side of the hole is not open. And the brother queue, his pipe to the left of the hole to put things, the right side of the pipe to take things.

4. How did mom and dad give birth to me and my brother?

As mentioned above, stacks and queues can be implemented through arrays or lists. Of course, parents create children, it is perfectly natural. So let's take a look at how I did it. As a data structure, I interface with IsEmpty (), size (), push (), pop (), Peek (), and Iterations.

Stack source code implementation:

public class Stack<item> implements iterable<item> {private item[] A;
   The array represents the stack, and the top of the stack is the largest subscript.            private int n;
       The number of elements in the stack/** * Initialize an empty stack/public stack () {a = (item[]) new object[2];
   n = 0;
   /** * Determine if there are elements in the stack/public boolean isempty () {return n = 0;
   /** * Returns the number of elements in the stack * * public int size () {return n;
       //Change the size of the stack private void resize (int capacity) {assert capacity >= N;
       Note You cannot create a generic array directly item[] temp = (item[]) new object[capacity];
       for (int i = 0; i < n; i++) {temp[i] = A[i];
      A = temp;
   You can also choose the following way to change the array size//A = Java.util.Arrays.copyOf (a, capacity); /** * Press the element */public void push (item) {//First determine the size of n, if the stack is full change the size of the stack if (n = = a.length) Resize    
       (2*a.length);                
   a[n++] = Item; /** * Eject and return element */public Item pop () {if (i)Sempty ()) throw new Nosuchelementexception ("Stack underflow");
       Item item = a[n-1];   A[N-1] = null;
       Prevent the object from free n--;
       If necessary, adjust the stack size if (n > 0 && n = a.length/4) resize (A.LENGTH/2);
   return item; /** * Returns but does not eject top of stack element */public Item peek () {if (IsEmpty ()) throw new Nosuchelementexception ("Stack und
       Erflow ");
   return a[n-1]; /** * Returns an iterator that can be advanced after iteration/public iterator<item> iterator () {return new Reversearrayiterato
   R (); 
   ////using internal classes to implement the iterator interface, realize the advanced iteration from top to bottom of stack, without implementing the Remove () method.
       Private class Reversearrayiterator implements iterator<item> {private int i;
       Public Reversearrayiterator () {i = n-1;
       public Boolean Hasnext () {return i >= 0;
       public void Remove () {throw new unsupportedoperationexception (); Public Item Next () {if (!hasnext ()) throw new nosuchelementexceptIon ();
       return a[i--]; }/** * Test/public static void main (string[] args) {stack<string> Stack = new stack<
       String> (); while (!
           Stdin.isempty ()) {String item = stdin.readstring ();
           if (!item.equals ("-")) Stack.push (item);
       else if (!stack.isempty ()) Stdout.print (Stack.pop () + "");
   } stdout.println ("(" + stack.size () + left on stack)); }
}

Again to see how to use a linked list to implement the stack:

public class Stack<item> implements iterable<item> {private node<item>;                Stack top node private int N;
       The number of elements in the stack//auxiliary class Node, used to form a list of private static class Node<item> {private item item;
   Private node<item> Next;
       }/** * Initialize stack */public stack () {first = null;
   N = 0;
       /** * To determine whether the stack is null/public Boolean IsEmpty () {return a null;
   return N = = 0;
   /** * Returns the number of elements in the stack * * public int size () {return N;
       /** * Press into element */public void push (item item) {Node<item> Oldfirst = i;
       The new node<item> ();
       First.item = Item;
       First.next = Oldfirst;
   n++; /** * Popup Element */Public Item pop () {if (IsEmpty ()) throw new Nosuchelementexception ("Stack underflow
       ");        Item item = First.item;            The element that needs to be ejected is the first.next;
  Delete Header node     n--;       
   return item; /** * Returns but does not eject element */public Item peek () {if (IsEmpty ()) throw new Nosuchelementexception ("Stack und
       Erflow ");
   return first.item;
       /** * Print elements from stack top to bottom stack/public String toString () {StringBuilder s = new StringBuilder ();
       for (item item:this) s.append (item + "");
   return s.tostring (); /** * Implement Iterable interface/public iterator<item> iterator () {return new Listiterator<item&gt
   ;(a);
       }//Implement iterator Interface for iterations, no Remove method is implemented private class Listiterator<item> implements Iterator<item> {

       Private node<item> current;
       When initialized, current points to the top of the stack public listiterator (node<item> first) {current = first;
       public Boolean Hasnext () {return current!= null;
       public void Remove () {throw new unsupportedoperationexception (); } public Item Next () {if (!hasnext ()) throw new Nosuchelementexception ();
           Item item = Current.item; 
           current = Current.next;
       return item; }/** * Test/public static void main (string[] args) {stack<string> s = new stack<st
       Ring> (); while (!
           Stdin.isempty ()) {String item = stdin.readstring ();
           if (!item.equals ("-")) S.push (item);
       else if (!s.isempty ()) Stdout.print (S.pop () + "");
   } stdout.println ("(" + s.size () + left on stack)); }
}

Also as a data structure of the younger brother, some interfaces need to be implemented: IsEmpty (), size (), Enqueue (), dequeue (), Peek (), and Iterations. Queues and stacks differ in that the row and the column are in two places, so two variables need to be maintained to represent the team head and the tail of the team.

Using arrays to implement queues:

public class Queue<item> implements iterable<item> {private item[] q;          private int N;      Number of elements in the queue private int-I;       The subscript of the team head element is private int last; The subscript of the rear of the team tail element, that is, the position where the element row can be placed/** * Initialize the queue, at this point the header and tail subscript coincide/public queue () {q = (item[]) new object[2]
       ;
       N = 0;
       i = 0;
   last = 0;
   /** * Still use N to determine whether the queue is empty */public Boolean isempty () {return n = 0;
   /** * The number of elements in the queue */public int size () {return N;
       //adjust array size private void resize (int max) {assert Max >= N;
       item[] temp = (item[]) new Object[max];
       Note here: Put N elements in a queue with a total size of max (max>=n)//Because loops use arrays, the first I elements from first may be saved in first//front (that is, last in front).
       for (int i = 0; i < N; i++) {Temp[i] = q[(i + i)% q.length];
       } q = temp;
       Reset the team head and team tail first = 0 by copying the small queues to the large queue in order
   last = N; }/** * Element row */Public VOID Enqueue (item Item) {if (N = = q.length) resize (2*q.length);   q[last++] = Item;  The element row if (last = = Q.length) is last = 0;
   If the last exceeds the array subscript, put the last zero, and loop through the array n++; }/** * Element column/public Item dequeue () {if (IsEmpty ()) throw new Nosuchelementexception ("Queue under
       Flow ");
       Item item = Q[first];       Q[first] = null;
       Prevent the object from free n--;
       first++; if (A/= Q.length)-0; 
       Iterate through the array, the next team header is labeled 0 where if (n > 0 && n = q.length/4) resize (Q.LENGTH/2);
   return item; /** * Returns the team head element but not the column * * Public Item Peek () {if (IsEmpty ()) throw new Nosuchelementexception ("Queue un
       Derflow ");
   return Q[first];
   /** * Implementation of the Iterable interface */public iterator<item> iterator () {return new arrayiterator (); ///Implement Iterator private class Arrayiterator implements iterator<item> {//Maintenance one I for iteration private int i = 0
       ; public Boolean Hasnext () {return i < N;}  public void Remove () {throw new unsupportedoperationexception (); ///Direct use of the A to traverse, note that there may be an array of loops using public Item next () {if (!hasnext ()) throw new Nosuchelementexce
           Ption ();
           Item item = q[(i + a)% q.length];
           i++;
       return item; }/** * Test/public static void main (string[] args) {queue <String> q = new Queue <st
       Ring> (); while (!
           Stdin.isempty ()) {String item = stdin.readstring ();
           if (!item.equals ("-")) Q.enqueue (item);
       else if (!q.isempty ()) Stdout.print (Q.dequeue () + "");
   } stdout.println ("(" + q.size () + left on queue)); }
}

Implement queues using linked lists:

public class Queue<item> implements iterable<item> {private node<item>;     Team head node private node<item> last;               Team Tail nodes (note that the last is not the subscript of the tail element) and the private int N;
       Number of queue elements//helper class Node private static class Node<item> {private item item;
   Private node<item> Next;
       /** * Initialization queue/public queue () {first = null;
       last = null;
   N = 0;
   public Boolean IsEmpty () {return-= NULL;     
   public int size () {return N; /** * Returns but does not delete the header element */Public Item peek () {if (IsEmpty ()) throw new Nosuchelementexception ("Queue und
       Erflow ");
   return first.item;
       }/** * Element row */public void Enqueue (item) {//Record tail node node<item> oldlast = Last;
       Create a new tail node last = node<item> ();
       Last.item = Item;
       Last.next = null; If the queue is empty, the front is set to last because the queueOnly one element of the IF (IsEmpty ()) first = last;
       Otherwise, perform normal operations to insert a new node in the tail node else Oldlast.next = last;
   n++; }/** * Element column/public Item dequeue () {if (IsEmpty ()) throw new Nosuchelementexception ("Queue under
       Flow ");
       Team HEAD Element Column item = First.item;
       i = First.next;
       n--;  
       If the queue is empty, which means that there is only one element, then the last is also set to NULL if (IsEmpty ()) = null;
   return item;
       Public String toString () {StringBuilder s = new StringBuilder ();
       for (item item:this) s.append (item + "");
   return s.tostring ();  
   Public iterator<item> iterator () {return new listiterator<item> (a);  //Implementation Iteration Private class Listiterator<item> implements iterator<item> {private node<item>
       Current
       To implement an iteration, we only need to maintain a node and, at the beginning, place it as the first public listiterator (node<item> primary) {current = single.

   }    public Boolean Hasnext () {return current!= null;}  public void Remove () {throw new unsupportedoperationexception ();
           Public Item Next () {if (!hasnext ()) throw new Nosuchelementexception ();
           Item item = Current.item; 
           current = Current.next;
       return item; }/** * Test/public static void main (string[] args) {queue<string> q = new queue<st
       Ring> (); while (!
           Stdin.isempty ()) {String item = stdin.readstring ();
           if (!item.equals ("-")) Q.enqueue (item);
       else if (!q.isempty ()) Stdout.print (Q.dequeue () + "");
   } stdout.println ("(" + q.size () + left on queue)); }
}

I am a stack, my twin brother is called the queue. My father is an array, my mother is a linked list. You can use arrays and lists to implement stacks and queues.

Well, today's story about me and my family is first introduced to you here. Secretly tell you a secret, in fact, between my brother and I can be converted to each other. That is, you can use stacks to implement queues, and you can also use queues to implement stacks.

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.