最近在看JAVA教學的視頻,覺得老師講的很好,同時借用源代碼還有筆記來撰寫本系列博客,記錄自己的學習內容,同時也供看到的人學習。
昨天生病了木有寫博文~今天繼續,第30篇,本篇內容的類型和上一篇是一樣的,模擬實現另外一種實現List接口的數據結構:雙向鏈表——LinkedList,還是直接呈上代碼,關於部分方法的解釋講解我已經添加到了代碼裏面,看此博文的小夥伴要仔細閱讀或者實現一下,便於我們更加深入地理解:
//用來表示一個節點
public class Node {
Node previous; //上一個節點
Object obj; //節點的本質(值)是Object型
Node next; //下一個節點
public Node() {
}
public Node(Node previous, Object obj, Node next) {
super();
this.previous = previous;
this.obj = obj;
this.next = next;
}
public Node getPrevious() {
return previous;
}
public void setPrevious(Node previous) {
this.previous = previous;
}
public Object getObj() {
return obj;
}
public void setObj(Object obj) {
this.obj = obj;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
package cn.bjsxt.collection;
public class SxtLinkedList /*implements List*/ {
private Node first; //獲得頭結點,之後按照Node的結構可以一直往後找
private Node last; //獲得當前鏈表的最後一個節點
private int size;
public void add(Object obj){
Node n = new Node();
if(first==null){ //鏈表中沒有任何結點的情況下
n.setPrevious(null); //因爲是頭結點所以Previous爲空
n.setObj(obj);
n.setNext(null); //後面由於暫時沒有結點所以也爲空
first = n; //目前第一個和最後一個都是該節點
last = n;
}else{
//直接往last節點後增加新的節點
n.setPrevious(last);
n.setObj(obj);
n.setNext(null);
last.setNext(n);
last = n;
}
size++;
}
public int size(){
return size;
}
private void rangeCheck(int index){
if(index<0||index>=size){
try {
throw new Exception();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public Object get(int index){ //2
rangeCheck(index);
// 0 1 2 3 4
Node temp = node(index);
if(temp!=null){
return temp.obj;
}
return null;
}
public Node node(int index){ //按索引找到相應節點的方法,實現List接口必須有的
Node temp = null;
if(first!=null){
if (index < (size >> 1)) { //如果索引號是前半部分的則從頭結點開始遍歷查找
temp = first;
for(int i=0;i<index;i++){
temp = temp.next;
}
}else{
temp = last; //如果索引號是後半部分的則從尾結點開始遍歷查找
for (int i = size - 1; i > index; i--){
temp = temp.previous;
}
}
}
// LinkedList l;
return temp;
}
public void remove(int index){
Node temp = node(index);
if(temp!=null){ //數據結構的知識,不再詳述~
Node up = temp.previous;
Node down = temp.next;
up.next = down;
down.previous = up;
size--;
}
}
public void add(int index,Object obj){
Node temp = node(index);
Node newNode = new Node();
newNode.obj = obj;
if(temp!=null){
Node up = temp.previous;
up.next = newNode;
newNode.previous = up;
newNode.next = temp;
temp.previous = newNode;
size++;
}
}
public static void main(String[] args) {
SxtLinkedList list = new SxtLinkedList();
list.add("aaa");
list.add("bbb");
// list.add(1,"BBBB");
list.add("ccc");
list.add("ddd");
list.add("eee");
// list.remove(1);
System.out.println(list.get(3));
}
}