学习数据结构的最好方法就是手动写一次,这样才能更好的理解原理。
public class Linker {
private final int FLAG = -9999;//标记为头元素。
private int value;
private Linker next;
public Linker() {
super();
this.value = FLAG;
}
@Override
public String toString() {
return "Linker{" +
"FLAG=" + FLAG +
", value=" + value +
", next=" + next +
'}';
}
public int getFLAG() {
return FLAG;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Linker getNext() {
return next;
}
public void setNext(Linker next) {
this.next = next;
}
/*
*<span style="font-family: Arial, Helvetica, sans-serif;">添加方法,把头元素的指针赋值给插入元素的指针。这样做有个问题就是插入进来的数据会始终排在第一个。所以会造成倒序。</span>
*/
public boolean add(int value){
Linker Linker = new Linker();
Linker.setValue(value);
Linker.next = this.next;
this.next = Linker;
return true;
}
public boolean remove(int index){
Linker temp = this.next;
int count = 0;
Linker prev = this;
while (temp != null && count <= index) {
if (count != index) {
count++;
prev = temp;
temp = temp.next;
continue;
}else {
prev.next = temp.next;
temp.next = null;
return true;
}
}
return false;
}
public boolean set(int index,int newValue){
Linker temp = this.next;
int count = 0;
while (temp != null && count <= index) {
if(count!=index){
temp = temp.next;
count++;
continue;
}else {
temp.setValue(newValue);
return true;
}
}
if (index > count)
throw new IndexOutOfBoundsException();
return false;
}
public Linker findAll(){
Linker temp = this.next;
while (temp != null) {
System.out.println(temp.value);
temp = temp.next;
}
return temp;
}
public int get(int index){
Linker temp = this.next;
int count = 0;
while (temp != null && count <= index) {
if (count != index) {
count++;
temp = temp.next;
continue;
} else {
return temp.value;
}
}
if (index > count)
throw new IndexOutOfBoundsException();
return -9999;
}
public static void main(String[] args) {
Linker Linker = new Linker();
Linker.add(1);
Linker.add(2);
Linker.add(3);
Linker.add(4);
Linker.add(5);
Linker.add(6);
// Linker.remove(0);
Linker.set(9, 8);
Linker.findAll();
// System.out.println(Linker.get(0));
}
}