java数据结构博客园_常见数据结构的Java实现

单链表的Java实现

首先参考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;

}

}

}

单链表翻转的Java实现

循环方式

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实现

fdf9fe10ad7134774c52b656cdb41b56.png

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;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值