Java beauty [from rookie to master evolution] of data structure base, linear table, stack and queue, array and string __arcinfo

Source: Internet
Author: User
Tags data structures int size prev static class

The data Structure Foundation of Java interview Book--linear table

Author: Egg

Email: xtfggef@gmail.com

Micro Blog: HTTP://WEIBO.COM/XTFGGEF

Blog: http://blog.csdn.net/zhangerqing (reprint please indicate the source)

This part of the content as the most basic knowledge of computer science, it is used by almost all enterprises to do the examination, therefore, we start from this chapter, we will be from the basis of the data structure to explain the main content is a linear table, including stacks, queues, arrays, strings, etc., mainly to explain the basic knowledge, such as concepts and simple implementation code, The nonlinear structure is given in the following article. In the process there is either

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


First, the data structure concept

With my understanding, the data structure contains a number and structure, the popular point is that the data in accordance with a certain structure, different combinations will have different efficiency, use different scenes, that's all. such as our most commonly used arrays, is a data structure, there is a unique way to host the information, in order, and its characteristics is that you can quickly find elements based on subscript, but because the insertion and deletion of elements in the array of other elements will be a large amount of cheap, so it will bring more consumption, so because of this feature, Makes the array suitable: The query is more frequent, the increase, the deletion ratio is few, this is the data structure concept. The data structure includes two kinds: linear structure and non-linear structure, linear structure includes: array, chain list, queue, stack, etc., nonlinear structure including tree, graph, table and so on and derivative class structure. In this chapter we first explain the linear structure, mainly from the array, linked list, queue, stack aspects of the discussion, NON-LINEAR data structures will continue to explain later.


Second, linear table

Linear table is the most basic, simplest and most commonly used data structure. The relationship between data elements in a linear table is one-to-one, that is, other data elements are end-to-end, except for the first and last data elements. The logical structure of linear table is simple and easy to implement and operate. Therefore, linear table is a kind of data structure which is widely used in practical application. Its basic operation mainly includes:

1) makeempty (l) This is a way of turning L into an empty table.
2 Length (L) Returns the size of the table L, that is, the number of elements in the table
3 Get (L,i) This is a function, the function value is the element of position I in L (1≤i≤n)
4) The precursor element of Prev (L,i)
5) Next (L,i) takes the successor element of I
6) Locate (l,x) This is a function, the function value is the position of element x in L
7 Insert (L,I,X) inserts element x at position I of table L and pushes the element of the original occupy position I and the elements behind it back one position
8) Delete (l,p) deletes the element at position p from table L
9) IsEmpty (L) Returns true if the table L is an empty table (length 0) or False
Clear (L) clears all elements
Init (L) with the first, initialize the linear table to null
Traverse (L) traverses all elements of the output
Find (L,x) finds and returns elements
Update (L,X) Modify elements
Sort (L) to reorder all elements by a given condition
Strstr (STRING1,STRING2) is used to string1 the first address of string2 in a character array.

Whichever way you implement a linear table, you should have at least one of these basic methods, and I'll follow the basic implementation of the data structure below.


Third, the basic data structure

A data structure is an abstract datatype (ADT), it can be said that we can use any way to achieve a data structure, as long as the data structure to be implemented, the data structure is a standard, we can use different ways to achieve, the most commonly used two are arrays and linked lists (including single linked list, Bidirectional linked list, etc.). Arrays are very common data types and are implemented in any language, and we use Java to simply implement arrays.
An array is an object of a reference type, and we can declare an array in such a way as the following:

	int a[];
	Int[] B;
	int []c;

        A = new int[10];

To sum up, the declaration of an array has a basic three factors: type, name, subscript, Java, the array is relatively flexible in format, subscript and name can be exchanged position, the first three cases we can understand as declaring a variable, the latter is assigned to it. Or, as in the following, assign a value at the time of the declaration:

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

I explain a little bit, in fact, if only execute: int[] B, just create a reference variable on the stack, not assigned value, only when the execution d = new int[10] will be in the heap real allocation of space. The first behavior of the above is statically initialized, that is, the user specifies the contents of the array, the system computes the size of the array, the second line is the opposite, the user specifies the size of the array, the system assigns the initial value, and we print the initial value of the array:

		int []d = new int[10];
		System.out.println (d[2]);
Result output 0, for an array of type int, the default initial value is 0.

However, there is absolutely no way to do this:

       int e[10] = new INT[10];
Unable to compile, as for why, the grammar is so, this is a specification, do not have to think about it.
We can retrieve the array by subscript. Let me give a simple example to illustrate the use of the following array.

	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, traversal, and the following 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 < 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--)
			ol D[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] = ol D[h + 1];
		}
		Old[old.length-1] = 0;
		return old;
	}

To write briefly, I would like to explain the principle of deleting and adding elements in an array: adding elements, moving the index back in turn, and then inserting the value into the index position, and then moving the values forward in the following order, which is simpler.

Remember that an array is a collection of data that represents the same type, and the subscript starts at 0.

Array implementation of the offline table can refer to ArrayList, the JDK attached to the source code, interested students can read. Below I briefly introduce the next single linked list.

Single linked list is the simplest linked list, there are nodes between the end of the connection, the simple schematic as follows:


In addition to the head node, each node contains a data field a pointer field, in addition to the head, tail node, each node pointer to the next node, we write an example to operate a single linked list.

Package com.xtfggef.algo.linkedlist; public class Linkedlist<t> {/** * class node * @author Egg * @param <T> * * private static Class No
		de<t> {T data;

		Node<t> Next;
			Node (T data, node<t> next) {this.data = data;
		This.next = Next;
		Node (T data) {This (data, null);

	}//Data private 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> (i
		TEM);
		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;
	Else System.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;
		The 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 ();
				else Prev.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; }
}

Single linked list is the best play is to add and delete nodes, the following two diagrams are used to represent the single chain table increase, deletion point schematic, looking at the figure learning, understand easier.


The next queue and stack, we are using a different structure to achieve, the queue with arrays, stack with a single list, readers interested in this, you can use different methods to achieve.


Four, the queue
A queue is a commonly used data structure, an advanced first-out, FIFO structure, that is, it can only be deleted at the table header, at the end of the table, and 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 \
		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 ()) {THR  
        ow 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 ()); }
}

Queues can only be deleted at the table header and added at the end of the table, which is a feature of the structure that applies to queueing systems.

Five, stack

The stack is a LIFO, first OUT,LIFO data structure, where we implement a stack using a single linked list.

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 of this chapter is very basic, focus on let reader friends understand the concept of data structure, the next chapter, we will introduce the tree, binary tree and other Java implementation, please readers to continue to pay attention to friends.

Author: Egg

Email: xtfggef@gmail.com

Micro Blog: HTTP://WEIBO.COM/XTFGGEF

Blog: http://blog.csdn.net/zhangerqing (reprint please indicate the source)


If you have any questions, please contact the author in accordance with the above contact method, and welcome the readers to make suggestions in time.

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.