首先参考wiki上的单链表说明,单链表每个节点包含数据和指向链表中下一个节点的指针或引用。然后看代码
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; } } }
循环方式
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);
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<SIZE;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; } }