java数据结构博客园_常见数据结构的Java实现
單鏈表的Java實現(xiàn)
首先參考wiki上的單鏈表說明,單鏈表每個節(jié)點包含數(shù)據(jù)和指向鏈表中下一個節(jié)點的指針或引用。然后看代碼
import java.lang.*;
public class SinglyLinkeList
{
Node start;
public SinnglyLinkedList()
{
this.start=null;
}
public void addFront(Object newData)
{
Node cache = this.start; //store a reference to the current start node
this.start = new Node(newData,cache); //assign our start to a new node that has newData and points to our old start
}
public addRear(Object newData)
{
Node cache = start;
Node current = null;
while((current = cache.next) != null) //find the last Node
cache = cache.next;
cache.next = new Node(newData,null); //create a new node that has newData and points to null
}
public Object getFront()
{
return this.start.data; // return the front object's data
}
public class Node
{
public Object data; //the data stored in this node
public Node next; //store a reference to the next node in this singlylinkedlist
public Node(Object data,Node next){
this.data =data;
this.next =next;
}
}
}
單鏈表翻轉(zhuǎn)的Java實現(xiàn)
循環(huán)方式
public static LinkedList reverse(LinkedList Node) {
LinkedList previous = null;
while (Node != null) {
LinkedList next = Node.next;
Node.next = previous;
previous = Node;
Node = next;
}
return previous;
}
package linkedlists;
public static LinkedList reverse(LinkedList node) {
LinkedList headNode = new LinkedList(1);
快速排序的Java實現(xiàn)
public class QuickSort {
public static int SIZE = 1000000;
public int[] sort(int[] input) {
quickSort(input, 0, input.length-1);
return input;
}
public static void main(String args[]){
int[] a = new int[SIZE];
for(int i=0;i
a[i] = (int)(Math.random()*SIZE);
}
QuickSort mNew = new QuickSort();
long start = System.currentTimeMillis();
mNew.sort(a);
long end = System.currentTimeMillis();
System.out.println("Time taken to sort a million elements : "+(end-start)+" milliseconds");
}
public void print(int[] inputData) {
for(int i:inputData){
System.out.print(i+" ");
}
System.out.println();
}
private void quickSort(int arr[], int left, int right) {
int index = partition(arr, left, right);
if (left < index - 1)
quickSort(arr, left, index - 1);
if (index < right)
quickSort(arr, index, right);
}
private int partition(int arr[], int left, int right) {
int i = left, j = right;
int tmp;
int pivot = arr[(left + right) / 2];
while (i <= j) {
while (arr[i] < pivot)
i++;
while (arr[j] > pivot)
j--;
if (i <= j) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
}
return i;
}
}
總結(jié)
以上是生活随笔為你收集整理的java数据结构博客园_常见数据结构的Java实现的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java实现未读消息提醒_Android
- 下一篇: java调用kafka接口发送数据_Ja