On algorithms and data structures: one stack and queue __java

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

Recently at home in the evening to see algorithems,4th Edition, I bought the English version, think this book is relatively easy to understand, and "figure Code and Mao", take advantage of this opportunity to learn to do notes, this will also be impressive, this is the reason for writing this series of articles. In addition, Princeton University also has this book in the Coursera of the Open class, there is another algorithm analysis course, the author of this course is also the author of this book, both courses are very good.

The computer program is inseparable from the algorithm and data structure, this paper introduces the stack (stack) and the implementation of queues (queue). NET in the data structure, typical applications, and so on, hoping to deepen their understanding of these two simple data structures. 1. Basic Concepts

The concept is simple, the stack is a OFF,LIFO data structure, and the queue is a first-in (FISRT) OUT,FIFO structure, as shown in the following diagram:

2. Implement

Now see how to implement the above two data structures. Before doing so, the Framework design guidelines This book tells us that when designing an API or entity class, the API specification should be written around the scene.

Implementation of the 1.1 stack

Stack is a last-in-first-out data structure, and for stack we want to provide at least the following methods:

Stack<t> ()

Create an empty stack

void Push (T s)

Add a new element to the stack

T Pop ()

Remove and return the most recently added element

Boolean IsEmpty ()

Whether the stack is empty

int Size ()

The number of elements in the stack

To implement these functions, we have two methods, arrays and linked lists, which look at the list implementation:

The chain list implementation of the stack:

We first define an inner class to hold the node for each linked list, which includes the current value and points to the next value, and then establishes a node that holds the value at the top of the stack and the number of elements in the record stack;

Class Node
{public
    T item{get;set;}
    Public Node Next {get; set;}
}
Private Node first = null;
private int number = 0;

Now to implement the Push method, which pushes an element to the top of the stack, first saves the original element at the top of the stack, creates a new top element of the stack, and then points the next element to the top of the stack. The entire pop process is as follows:

The implementation code is as follows:

void Push (T node)
{
    node oldfirst = first;
    First = new Node ();
    First. item= node;
    First. Next = Oldfirst;
    number++;
}

The Pop method is also very simple, first save the value of the top element of the stack, and then set the top element of the stack to the next element:

T Pop ()
{
    T item = first. Item;
    First = first. Next;
    number--;
    return item;
}

A linked list-based stack implementation, in the worst case, requires only constant time for push and pop operations.

Array implementations of Stacks:

We can use the array to store the elements in the stack when push, add an element directly s[n] to the array, the pop directly back to s[n-1].

First, we define an array and then, given the initialization size in the constructor, the push method implements the following, which is the addition of an element in the collection:

T[] Item;
int number = 0;

public Stackimplementbyarray (int capacity)
{
    item = new t[capacity];
}
public void Push (T _item)
{
    if (number = = Item. Length) Resize (2 * item. Length);
    item[number++] = _item;
}

Pop method:

Public T Pop ()
{
    T temp = item[--number];
    Item[number] = default (T);
    if (number > 0 && Number = = Item. LENGTH/4) Resize (item. LENGTH/2);
    return temp;
}

In the push and pop methods, in order to save memory space, we will organize the array. When pushing, when the number of elements reaches the capacity of the array, we open up a new array of twice times the current element, and then copy the elements from the original array into the new array. Pop, when the number of elements is less than 1/4 of the current capacity, we reduce the size capacity of the original array by 1/2.

The Resize method is basically an array copy:

private void Resize (int capacity)
{
    t[] temp = new t[capacity];
    for (int i = 0; i < item. Length; i++)
    {
        Temp[i] = Item[i];
    }
    item = temp;
}

When we narrow the array, we use the case of judging 1/4, so that the efficiency is higher than 1/2, because it can effectively avoid inserting, deleting, inserting, deleting in 1/2 attachments, so as to enlarge and narrow the array frequently. The following illustration shows the elements in the array and the size of the array in the case of insertions and deletions:

Analysis: 1. The times when the pop and push operations are at worst proportional to the number of elements, the time is mainly spent on the array copy when enlarging or shrinking the number of arrays.

2. The elements are compact in memory, high density, easy to take advantage of memory time and spatial locality, easy to cache the CPU, less linklist memory consumption, high efficiency.

Implementation of the 2.2 queue

Queue is an advanced first-out data structure, like a stack, he also has a list and array of two implementations, understanding the implementation of the stack, the implementation of the queue is relatively simple.

Stack<t> ()

To create an empty queue

void Enqueue (T s)

Add a new element to the queue

T Dequeue ()

Remove the oldest added element in a queue

Boolean IsEmpty ()

Whether the queue is empty

int Size ()

Number of elements in the queue

First look at the implementation of the linked list:

The Dequeue method is to return the first element in the list, similar to the Pop method in the stack:

Public T Dequeue ()
{
    T temp = first. Item;
    First = first. Next;
    number--;
    if (Isempety ()) Last
        = null;
    return temp;
}

Unlike the push method of stack, Enqueue adds a new element at the end of the list:

public void Enqueue (T item)
{
    Node oldlast = last;
    last = new Node ();
    Last. item = Item;
    if (Isempety ())
    {First
        = last;
    }
    else
    {
        oldlast.next = last;
    }
    number++;
}

Again, now look at how to use arrays to implement queue, first we use arrays to hold data, and define variables head and tail to record the end-to-end elements of a queue.

Unlike stack implementations, in the queue, we define head and tail to record header and tail elements. When Enqueue, the Tial plus 1, the element is placed in the tail, when Dequeue, head minus 1, and return.

public void 

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.