Basic data Structure (1)--Introduction to Algorithms (11)

Source: Internet
Author: User
Tags decrypt

1. Introduction

Start with this blog to introduce some basic data structure knowledge. This article and the next one will introduce several basic data structures: Stacks, queues, linked lists, and root trees. Methods for constructing objects and pointers from arrays are also described.

This article mainly introduces stacks and queues, both of which are dynamic collections .

From the logical structure of the data, the elements removed by the delete operation on them are fixed: in the stack, the most recently inserted element (last in, first out , lifo,last-in,first-out) is removed, while in the queue , the element being removed is the first element to be inserted ( FIFO , fifo,first-in,first-out).

From the storage structure of the data, they can all be implemented using sequential structure storage and chained structure storage (although in later diagrams, they are drawn in the form of arrays).

2. Stacks (Stack)

The insert operation on the stack is called push (press-in, stack), and the delete operation is called pop (eject, out-stack). There are many "structures" in real life that are similar to stacks. such as a magazine (the bullet that was stuffed into the magazine is first played), a stack of stacked plates (we can only take out the top plate at a time) and so on.

For example, a stack s is in the push and pop operations. The stack has a property top (the top pointer of the stack) that is used to mark (point) The top element of the stack . Note: Sometimes when we implement push or pop operations, it is not really necessary to add or remove an element on the physical storage structure (because this brings additional overhead, and of course, it needs to be done), but it can be achieved by moving the top pointer of the stack.

If there are no elements in the stack, we call the stack empty (empty), and if you attempt a pop operation on an empty stack, it is called Stack underflow (underflow), instead, if you try to push with a stack that has a size of N, and top already points to position n is called stack overflow (overflow);

The pseudo-code for implementing the stack is given below (without considering the overflow problem of the stack):

One of the classic applications of stacks is to retrieve a string of positive and negative brackets in strings that contain only the positive and negative brackets (the concept of matching is: Just as we write code, the positive and negative brackets must match, no matter how layers are nested). This is done by traversing the string to be retrieved, and pushing the positive brackets into the stack when we encounter the parentheses, and the pop operation against the stack when we encounter the parentheses. If a stack underflow error is encountered during traversal or the stack is not empty after traversal, the positive and negative brackets in the string are mismatched;

The Java implementation code is given below:

 Public classMain11 { Public Static voidMain (string[] args) {System.out.println (Checkbrackets ("()((())")); System.out.println (Checkbrackets ("())(())")); System.out.println (Checkbrackets ("()(())")); }    /*** Check if the parentheses in str match * *@paramSTR *@return     */     Public Static Booleancheckbrackets (String str) {if(str = =NULL||Str.isempty ()) {            Throw NewNullPointerException ("String to be detected cannot be empty"); }        if(!str.matches ("\ \ \]+"))) {            Throw NewRuntimeException ("The character being detected cannot contain characters other than ' (', ') '"); } Stack<Character> stack =NewStack<character>();  for(inti = 0; I < str.length (); i++) {            Charc =Str.charat (i); if(c = = ' (') {Stack.push (c); } Else {                Try{stack.pop (); } Catch(Exception e) {return false; }            }        }        returnStack.isempty (); }}/*** <p> * stack * </p> * <p> * This is just a simple encapsulation of linkedlist to simulate a stack structure * </p> *@authorD.K * *@param<T>*/classStack<t> {    PrivateLinkedlist<t>list;  PublicStack () {list=NewLinkedlist<>(); }     Public BooleanIsEmpty () {returnList.isEmpty (); }     Public voidpush (T-t) {list.addlast (t); }     PublicT Pop () {returnList.removelast (); }}

Results:

3. Queuing (queue)

Insert operations on a queue are called enqueue(queued), while delete is called dequeue(out-of-pair). In real life, the team that we arrange when we checkout is like a queue data structure (the first person is in front of the column, the checkout is first, leaving).

For example, the process of enqueue and dequeue operations is described in queue Q. The queue has head (header) and tail (tail of the team ). The elements in the queue are stored between Q.head and Q.TAIL-1. The queue is connected (rounded). Initially, Q.head = Q.tail = 1. When q.head = Q.tail, the queue is empty and if an attempt is made to remove an element from an empty queue, a queue underflow occurs, and when q.head = Q.tail+1, the queue is full, and the queue overflow occurs if an element is attempted to be inserted in the full queue.

The following is a pseudo-code for the implementation of the queue (omitting overflow checking)

Let's look at an example of an application queue. (Example from: http://www.cnblogs.com/shenliang123/archive/2013/02/16/2913552.html)

In cryptography, the Caesar cipher is one of the simplest and most widely known cryptography techniques. It is rumored that the ancient Roman Julius Caesar was used to protect the vital intelligence of the encryption system (not very credible). Its practice is to encrypt each letter of the English string to be encrypted by moving a certain number of bits in the order of the alphabet. This is easy to crack because there are only 25 moving scenarios (assuming that each letter moves the same number of digits).

Now let's consider a similar but slightly more reliable way of encrypting (in fact, it is easy to decipher the frequency of the letters). Let's start by agreeing on a set of keys (stored in a queue), and then moving each character to the right in alphabetical order to move the number in the corresponding position in the key. The Java implementation code is given below:

 Public classmain11_2 { Public Static Finalinteger[] Secret_key =NewInteger[] {-1, 3, 2, 5, 9, 0 };  Public Static voidMain (string[] args) {String originaltext= "Good good Study,day day up!"; System.out.println ("The original is:" +originaltext); //EncryptString ciphertext =Encrypt (originaltext); System.out.println ("Ciphertext is:" +ciphertext); //decryptionString plaintext =decrypt (ciphertext); System.out.println ("Clear Text is:" +plaintext); }    /*** Encryption * *@paramPlainText * Clear text *@returnCiphertext*/    Private Staticstring Encrypt (string plaintext) {string ciphertext= ""; if(PlainText = =NULL||Plaintext.isempty ()) {            returnciphertext; } Queue<Integer> queue =NewQueue<>(Secret_key);  for(inti = 0; I < plaintext.length (); i++) {            Charc =Plaintext.charat (i); intKey =Queue.dequeue (); Ciphertext+= (Char) (C +key);        Queue.enqueue (key); }        returnciphertext; }    /*** Decryption * *@paramciphertext * Secret text *@returnplaintext*/    Private Staticstring Decrypt (String ciphertext) {string plaintext= ""; if(Ciphertext = =NULL||Ciphertext.isempty ()) {            returnplaintext; } Queue<Integer> queue =NewQueue<>(Secret_key);  for(inti = 0; I < ciphertext.length (); i++) {            Charc =Ciphertext.charat (i); intKey =Queue.dequeue (); PlainText+= (Char) (C-key);        Queue.enqueue (key); }        returnplaintext; }}classQueue<e> {    PrivateLinkedlist<e>list;  PublicQueue () { This(NULL); }     PublicQueue (e[] objs) {list=NewLinkedlist<>(); if(Objs! =NULL) {             for(e e:objs) {enqueue (e); }        }    }     Public BooleanIsEmpty () {returnList.isEmpty (); }     Public voidEnqueue (e e) {list.addlast (e); }     PublicE dequeue () {returnList.removefirst (); }}

Results:

Basic data Structure (1)--Introduction to Algorithms (11)

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.