java 算法

1 二分法查找

import java.util.Scanner;




public class TestBinarySearch {
public static int rank(int[] num,int key){
int s = 0;
int e = num.length-1;
while(s<e){
int m = s+(e-s)/2;
if(key<num[m]){
e = m-1;
}else if(key>num[m]){
s = m+1;
}else if(key == num[m]){
return m;
}
}
return -1;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("请输入数组长度:");
int l = s.nextInt();
System.out.println("请输入数:");
int[] num = new int[l];
for(int i = 0;i<l;i++){
num[i] = s.nextInt();
}
System.out.println("请输入要查数:");
int key = s.nextInt();
rank(num,key);
System.out.println("要查数位置:"+rank(num,key));
}


}

运算结果:

请输入数组长度:
4
请输入数:
3
4
5
6
请输入要查数:
4
要查数位置:1

2 单链表的反转

public class TestNodee {
public static void main(String[] args) {
Nodee head = new Nodee(0);
Nodee n1 = new Nodee(1);
Nodee n2 = new Nodee(2);
Nodee n3 = new Nodee(3);
head.setNext(n1);
n1.setNext(n2);
n2.setNext(n3);
Nodee h = head;
while(h != null){
System.out.println(h.getData());
h = h.getNext();
}
Nodee h1 = rehead(head);
while(h1 != null){
System.out.println(h1.getData());
h1 = h1.getNext();
}
}
public static Nodee rehead(Nodee head){
if(head == null){
return head;
}
Nodee pre = head;
Nodee cur = head.getNext();
Nodee temp;
while(cur != null){
temp=cur.getNext();
cur.setNext(pre);

pre = cur;
cur = temp;

}
head.setNext(null);
return pre;

}


}


class Nodee{
private int data;
private Nodee next;
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Nodee getNext() {
return next;
}
public void setNext(Nodee next) {
this.next = next;
}
/**
* @param data
*/
public Nodee(int data) {
super();
this.data = data;
}

}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值