数据结构
栈
public class Stack {
private int[] array = new int[5];// 栈
private int top = -1;// 指针
// 压栈
public boolean push(int x) {
if(top<array.length-1){
array[++top] = x;
return true;
}else{
throw new RuntimeException("overFlow");//上溢
}
}
// 出栈
public int pop() {
if (!isEmpty()) {
return array[top--];
} else {
throw new RuntimeException("underflow");//下溢
}
}
// 是否为空
public boolean isEmpty() {
return top == -1 ? true : false;
}
}
队列
public class Queue {
Object[] array = new Object[4]; // 对象数组,队列最多存储3个对象
int first = 0; // 队首下标
int last = 0; // 队尾下标;指向指向即将添加的下一个元素位置
/**
* 将一个对象追加到队列尾部
* @return 队列满时返回false,否则返回true
*/
public boolean add(Object obj) {
if ((last + 1) % array.length == first) {
return false;
}
array[last] = obj;
last = (last + 1) % array.length;
return true;
}
/**
* 队列头部的第一个对象出队
* @return 出队的对象,队列空时返回null
*/
public Object remove() {
if (last == first) {
return null;
}
Object obj = array[first];
first = (first + 1) % array.length;
return obj;
}
}
单向链表
public class LinkedList {
public Node head = null;
public void add(int x) {
Node node = new Node(x, null);
Node p = head;
// 注意链表为空的时候的插入
if (head == null) {
head = node;
}
// 尾插法
else {
while (p.next != null) {
p = p.next;
}
p.next = node;
}
}
/**
* 遍历打印
*/
public void travese(Node head) {
Node p = head;
while (p != null) {
System.out.println(p.item);
p = p.next;
}
}
/*
* 元素
*/
private static class Node {
int item;
Node next;
public Node(int item, Node next) {
this.item = item;
this.next = next;
}
}
}
算法
排序
/** 冒泡排序 大数向后 */
public static void bubbleSort(int[] ary) {
for (int i = 0; i < ary.length - 1; i++) {// length-1次,最后一个不用冒了.
for (int j = 0; j < ary.length - 1 - i; j++) {
if (ary[j] > ary[j + 1]) {
int t = ary[j]; ary[j] = ary[j + 1];ary[j + 1] = t;
}
}
}
}
/**选择排序 每次选出最小的数放前面 */
public static void selectionSort(int[] ary) {
for(int i=0;i<ary.length-1;i++){
for(int j=i+1;j<ary.length;j++){
if(ary[i]>ary[j]){
int t = ary[i]; ary[i] = ary[j];ary[j] = t;
}
}
}
}
/**插入排序 */
public static void insertSort(int[] ary){
int t,i,j;
for(i=1;i<ary.length;i++){
System.out.println(Arrays.toString(ary));
t = ary[i];
for(j=i-1;j>=0&&ary[j]>t;j--){
ary[j+1] = ary[j];
}
ary[j+1] = t;
}
}
二分法查找
/*
* 二分查找 简介:在左边的数;如果搜寻的数大于所搜寻的对象,则右边的数无需再搜寻,直接搜寻左边的数。
*/
public static int search(int[] nums, int num) {
int low = 0;
int high = nums.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
// 与中间值比较确定在左边还是右边区间,以调整区域
if (num > nums[mid]) {
low = mid + 1;
} else if (num < nums[mid]) {
high = mid - 1;
} else {
return mid;
}
}
return -1;
}
位运算
计算机中的数都是二进制表示的,以8位的byte类型表示为例
5 = 00000101(最高位表示符号,0位正,1为负)
无论>>还是>>>都是针对二进制数进行操作的。1、 右移运算符>>使指定值的所有位都右移规定的次数。
右边移出去的部分扔掉不要,左边空出来的部分用原来的数字填充(这就是所谓的带符号右移)比如说5,右移后为00000010。
你给的例子,假设x=-12,表示为32位int型就是
11111111111111111111111111110100
x>>3即带符号右移3位,结果是
11111111111111111111111111111101,化为十进制等于-32、>>>与>>唯一的不同是它无论原来的最左边是什么数,统统都用0填充。**
比如你的例子,byte是8位的,-1表示为byte型是11111111(补码表示法)
b>>>4就是无符号右移4位,即00001111,这样结果就是15。