The beauty of Java [from cainiao to masters]: Data Structure basics, linear tables, stacks and queues, arrays and strings

Source: Internet
Author: User

The basis of the data structure in the Java interview book-linear table

Author: Egg

Email: xtfggef@gmail.com

Weibo: http://weibo.com/xtfggef

Blog: http://blog.csdn.net/zhangerqing (reprinted please explain the source)

As the most basic knowledge of computer science, this part of content is selected by almost all enterprises for examination. Therefore, we will explain the data structure from the basic aspects starting from this chapter, the content is mainly a linear table, including stacks, queues, arrays, strings, etc. It mainly describes basic knowledge, such as concepts and simple implementation code, and non-linear structures. Any

What problems, please contact me: http://weibo.com/xtfggef

I. Data Structure Concept

In my understanding, the data structure includes data and structure. The common point is to combine the data according to a certain structure. Different Combinations have different efficiency and use different scenarios. For example, the most commonly used array is a data structure with a unique way of carrying data and arranged in order. It features that you can quickly search for elements by subscript, however, insertion and deletion of elements in an array may result in a relatively low cost of other elements, resulting in a large amount of consumption. Therefore, this feature makes the array suitable: queries are frequent, this is the concept of data structure. Data structures include linear structures and Non-linear structures, including arrays, linked lists, queues, and stacks. Non-linear structures include trees, graphs, tables, and classification structures. In this chapter, we will first explain the linear structure, mainly from the aspects of arrays, linked lists, queues, and stacks. The non-linear data structure will be explained later.


Ii. Linear table

A linear table is the most basic, simple, and commonly used data structure. The relationship between data elements in a linear table is one-to-one, that is, except the first and last data elements, other data elements are connected at the beginning and end. The logical structure of a linear table is simple for implementation and operation. Therefore, the linear table data structure is widely used in practical applications. The basic operations are as follows:

1) makeempty (l) is a method to change l to an empty table.
2) length (L) returns the length of table l, that is, the number of elements in the table.
3) Get (L, I) is a function. The function value is the element at position I in L (1 ≤ I ≤ n)
4) Prev (L, I) takes the precursor element of I.
5) Next (L, I) gets the successor element of I.
6) locate (L, x) is a function. The function value is the position of element x in L.
7) insert (L, I, x) insert element x at position I of table l, and push the elements occupying position I and the elements following it backward.
8) Delete (L, P) deletes the element at position P from table L.
9) isempty (l) If table L is empty (Length: 0), true is returned; otherwise, false is returned.
10) Clear (l) Clear all elements
11) Init (l) is the same as the first one. The initialized linear table is empty.
12) traverse (l) traverses and outputs all elements
13) Find (L, x) find and return Elements
14) Update (L, x) to modify elements
15) sort (l) sorts all elements by the given conditions again
16) strstr (string1, string2) is used to find the first address of string2 in string1 in the character array.

No matter which method is used to implement a linear table, at least these basic methods should be available. Below I will explain the basic implementation methods of the data structure.


III. Basic Data Structure

The data structure is an abstract data type (ADT). In this case, we can implement a data structure in any way, as long as it meets the features of the data structure to be implemented, data structure is a standard. We can implement it in different ways. The two most common methods are arrays and linked lists (including single-chain tables and two-way linked lists ). Arrays are very common data types. They are implemented in any language. Here we use Java to implement arrays.
An array is a reference type object. We can declare an array in the following way:

int a[];int[] b;int []c;

        a = new int[10];

To sum up, there are three basic elements for declaring an array: type, name, subscript. in Java, the array is relatively flexible in format, and the subscript and name can be exchanged, the first three cases can be understood as declaring a variable, and the last one assigns a value to it. Or assign a value during the declaration as follows:

int c[] = {2,3,6,10,99};int []d = new int[10];

I will explain a little. In fact, if only int [] B is executed, only a reference variable is created on the stack and no value is assigned, only when D = new int [10] is executed will the space be allocated on the stack. The first static initialization behavior indicates that the User specifies the content of the array and the system calculates the size of the array. The second row is the opposite. The User specifies the size of the array and the system allocates the initial value, let's print the initial values of the array:

int []d = new int[10];System.out.println(d[2]);

The output result is 0. For an array of the int type, the default initial value is 0.

However, it cannot be as follows:

       int e[10] = new int[10];

It cannot be compiled. As for the reason, the syntax is like this. This is a standard and you don't have to think about it.
We can use subscript to retrieve arrays. The following is a simple example to illustrate the usage of arrays.

public static void main(String[] args) {String name[];name = new String[5];name[0] = "egg";name[1] = "erqing";name[2] = "baby";for (int i = 0; i < name.length; i++) {System.out.println(name[i]);}}

This is the simplest example of array declaration, creation, assignment, and traversal. Here is an example of adding and deleting.

package com.xtfggef.algo.array;public class Array {public static void main(String[] args) {int value[] = new int[10];for (int i = 0; i < 10; i++) {value[i] = i;}// traverse(value);// insert(value, 666, 5);delete(value, 3);traverse(value);}public static int[] insert(int[] old, int value, int index) {for (int k = old.length - 1; k > index; k--)old[k] = old[k - 1];old[index] = value;return old;}public static void traverse(int data[]) {for (int j = 0; j < data.length; j++)System.out.print(data[j] + " ");}public static int[] delete(int[] old, int index) {for (int h = index; h < old.length - 1; h++) {old[h] = old[h + 1];}old[old.length - 1] = 0;return old;}}

To briefly describe how to delete and add elements to an array: to add an element, you need to move the index backward and insert the value to the index position, deleting is easier to move the following values forward in sequence.

Remember: arrays represent a set of data of the same type. The subscript starts from 0.

For offline tables of Array Implementation, refer to arraylist. The source code is included in JDK. If you are interested, read it. Next, I will briefly introduce the single linked list.

A single-chain table is the simplest linked list, which is composed of the first and last links between nodes. The following is a simple example:

In addition to the header node, each node contains a data field and a pointer field. In addition to the header and tail nodes, each node Pointer Points to the next node. Let's write an example to operate on a single-chain table.

package com.xtfggef.algo.linkedlist;public class LinkedList<T> {/** * class node * @author egg * @param <T> */private static class Node<T> {T data;Node<T> next;Node(T data, Node<T> next) {this.data = data;this.next = next;}Node(T data) {this(data, null);}}// dataprivate Node<T> head, tail;public LinkedList() {head = tail = null;}/** * judge the list is empty */public boolean isEmpty() {return head == null;}/** * add head node */public void addHead(T item) {head = new Node<T>(item);if (tail == null)tail = head;}/** * add the tail pointer */public void addTail(T item) {if (!isEmpty()) { tail.next = new Node<T>(item);tail = tail.next;} else { head = tail = new Node<T>(item);}}/** * print the list */public void traverse() {if (isEmpty()) {System.out.println("null");} else {for (Node<T> p = head; p != null; p = p.next)System.out.println(p.data);}}/** * insert node from head */public void addFromHead(T item) {Node<T> newNode = new Node<T>(item);newNode.next = head;head = newNode;}/** * insert node from tail */public void addFromTail(T item) {Node<T> newNode = new Node<T>(item);Node<T> p = head;while (p.next != null)p = p.next;p.next = newNode;newNode.next = null;}/** * delete node from head */public void removeFromHead() {if (!isEmpty())head = head.next;elseSystem.out.println("The list have been emptied!");}/** * delete frem tail, lower effect */public void removeFromTail() {Node<T> prev = null, curr = head;while (curr.next != null) {prev = curr;curr = curr.next;if (curr.next == null)prev.next = null;}}/** * insert a new node * @param appointedItem * @param item * @return */public boolean insert(T appointedItem, T item) {Node<T> prev = head, curr = head.next, newNode;newNode = new Node<T>(item);if (!isEmpty()) {while ((curr != null) && (!appointedItem.equals(curr.data))) {prev = curr;curr = curr.next;}newNode.next = curr; prev.next = newNode;return true;}return false; }public void remove(T item) {Node<T> curr = head, prev = null;boolean found = false;while (curr != null && !found) {if (item.equals(curr.data)) {if (prev == null)removeFromHead();elseprev.next = curr.next;found = true;} else {prev = curr;curr = curr.next;}}}public int indexOf(T item) {int index = 0;Node<T> p;for (p = head; p != null; p = p.next) {if (item.equals(p.data))return index;index++;}return -1;}/** * judge the list contains one data */public boolean contains(T item) {return indexOf(item) != -1;}}

Adding or deleting nodes is the most important part of a single-link table. The two charts below use graphs to represent the addition and deletion of nodes in a single-link table. It is easier to understand the chart!

The following queues and stacks are implemented using different structures. Queues use arrays and stacks use a single list. Readers are interested in this. You can use different methods to achieve this.


4. Queue
A queue is a common data structure. It is a first in first out (FIFO) structure. In other words, it can only be deleted from the header and added at the end of the table, below we implement a simple queue.

package com.xtfggef.algo.queue;import java.util.Arrays;public class Queue<T> {private int DEFAULT_SIZE = 10;private int capacity;private Object[] elementData;private int front = 0;private int rear = 0;public Queue(){capacity = DEFAULT_SIZE;elementData = new Object[capacity];}public Queue(T element){this();elementData[0] = element;rear++;}public Queue(T element , int initSize){this.capacity = initSize;elementData = new Object[capacity];elementData[0] = element;rear++;}public int size(){return rear - front;}public void add(T element){if (rear > capacity - 1){throw new IndexOutOfBoundsException("the queue is full!");}elementData[rear++] = element;}    public T remove(){if (empty()){throw new IndexOutOfBoundsException("queue is empty");}@SuppressWarnings("unchecked")T oldValue = (T)elementData[front];elementData[front++] = null; return oldValue;}        @SuppressWarnings("unchecked")public T element()      {          if (empty())          {              throw new IndexOutOfBoundsException("queue is empty");          }          return (T)elementData[front];      }  public boolean empty(){return rear == front;}public void clear(){Arrays.fill(elementData , null);front = 0;rear = 0;}public String toString(){if (empty()){return "[]";}else{StringBuilder sb = new StringBuilder("[");for (int i = front  ; i < rear ; i++ ){sb.append(elementData[i].toString() + ", ");}int len = sb.length();return sb.delete(len - 2 , len).append("]").toString();}}public static void main(String[] args){Queue<String> queue = new Queue<String>("ABC", 20);queue.add("DEF");queue.add("egg");System.out.println(queue.empty());System.out.println(queue.size());System.out.println(queue.element());queue.clear();System.out.println(queue.empty());System.out.println(queue.size());}}

The queue can only be deleted from the header and added at the end of the table. This structure is applicable to the queuing system.

V. Stack

Stack is a data structure of last in first out (LIFO). We use a single linked list to implement a stack.

package com.xtfggef.algo.stack;import com.xtfggef.algo.linkedlist.LinkedList;public class Stack<T> {static class Node<T> {T data;Node<T> next;Node(T data, Node<T> next) {this.data = data;this.next = next;}Node(T data) {this(data, null);}}@SuppressWarnings("rawtypes")static LinkedList list = new LinkedList();@SuppressWarnings("unchecked")public T push(T item) {list.addFromHead(item);return item;}public void pop() {list.removeFromHead();}public boolean empty() {return list.isEmpty();}public int search(T t) {return list.indexOf(t);}public static void main(String[] args) {Stack<String> stack = new Stack<String>();System.out.println(stack.empty());stack.push("abc");stack.push("def");stack.push("egg");stack.pop();System.out.println(stack.search("def"));}}

The content in this chapter is very basic and focuses on letting readers understand the concept of data structure. At the beginning of this chapter, we will introduce the implementation of trees, binary trees, and other Java. Please stay tuned!

Author: Egg

Email: xtfggef@gmail.com

Weibo: http://weibo.com/xtfggef

Blog: http://blog.csdn.net/zhangerqing (reprinted please explain the source)

If you have any questions, please contact the author based on the above contact information. You are welcome to give suggestions in time. Thank you!

Related Article

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.