arraylist
package test;
public class MyArraylist {
private Object[] array;
//添加
public void add(Object ob) {
//如果没有就添加一个
if (array == null) {
array = new Object[1];
array[0] = ob;
} else if (array.length > 0) {
//如果有了在原有的长度+1 new一个新对象
//采用倒水缸模式 将之前的数据代到新的数组再帮添加的数据带进去
//再把最新的数据赋值给array
Object[] newarray = new Object[array.length + 1];
for (int i = 0; i < array.length; i++) {
newarray[i] = array[i];
}
newarray[array.length] = ob;
array = newarray;
}
}
//获取长度
public Integer size() {
return array.length;
}
//删除
public boolean delete(Integer index) {
//new一个长度减一的数组因为每次都要删除一次
Object[] delete = new Object[array.length - 1];
//长度为少的
//因为我们删除某个数据就代表会少执行一次
for (int i = 0; i < delete.length; i++) {
//如果是我们要删除的那个就给长度+1赋值 相当于跳过他
if (i >= index) {
System.out.println(1);
delete[i] = array[i + 1];
} else {
delete[i] = array[i];
}
}
array = delete;
return true;
}
//获取数组里的数据
public void getAll() {
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
}
//获取某个下表下的数据
public Object get(int index) {
return array[index];
}
//修改
public boolean set(int index, Object ob) {
if (index < 1) {
return false;
}
if (index > array.length) {
return false;
}
array[index] = ob;
return true;
}
}
链表
node
package test.linknode;
public class Node {
public Object data;
public Node next;
public Node last;
public Node prev;
public Node(Object data) {
this.data = data;
}
public Node() {
}
}
LinkedList
package test.linknode;
import test.MyArraylist;
public class MyLinkedList {
//根节点 找到链表的唯一途径
private Node root;
/*
尾部
新增
*/
public void add(Object data) {
Node node = new Node(data);
if (root == null) {
root = node;
} else {
Node temp = root;
while (temp.next != null) {
temp = temp.next;
}
temp.next = node;
}
}
/*
遍历输出整个链表的方法
*/
public void getAll() {
Node temp = root;
while (temp.next != null) {
System.out.println(temp.data);
temp = temp.next;
}
System.out.println(temp.data);
}
/***
* 删除
* @param ob
*/
public void delete(Integer ob) {
if (ob == 0) {
root = root.next;
} else {
//找到删除位置的上一个
int num = 0;
Node temp = root;
while (temp != null) {
if (num == ob - 1) {
temp.next = temp.next.next;
break;
}
temp = temp.next;
num++;
}
}
}
public void update(int index, Object data) {
int num = 0;
Node temp = root;
while (temp != null) {
if (num == index)
temp.data = data;
temp = temp.next;
num++;
}
}
public void get(int index) {
int num = 0;
Node temp = root;
while (temp.next != null) {
if (num == index) {
System.out.println(temp.data);
}
num++;
temp = temp.next;
}
}
public void addFirst(Object data1) {
Node n = new Node(data1);
n.next = root;
root = n;
}
public void addindex(Integer index, Object data) {
Node node = new Node(data);
if (index == 0) {
node.next = root;
} else {
int i = 0;
Node temp = root;
while (temp != null) {
if (i == index - 1) {
node.next = temp.next;
temp.next = node;
break;
}
temp = temp.next;
i++;
}
}
}
}