JAVA 手動實現LinkedList

JAVA 手動實現LinkedList

節點

package com.ghg.data_structure.link;

public class Node<T> {
    /**
     * 數據
     */
    public T data;
    /**
     * 前一個
     */
    public Node pre;
    /**
     * 后一個
     */
    public Node next;


    public Node() {
        super();
    }
    
    /**
     * 
     * @param data 數據
     * @param pre 前一個
     */
    public Node(T data, Node pre, Node next) {
        super();
        this.data = data;
        this.pre = pre;
        this.next = next;
    }


    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public Node getPre() {
        return pre;
    }

    public void setPre(Node pre) {
        this.pre = pre;
    }

    public Node getNext() {
        return next;
    }

    public void setNext(Node next) {
        this.next = next;
    }

    @Override
    public String toString() {
        return data+" ";
    }
}

List接口

package com.ghg.data_structure.link;

public interface MyList<T> {

    /**
     * 是否為空
     * @return
     */
    public boolean isEmpty();

    /**
     * 大小
     * @return
     */
    public int size();

    /**
     * 添加到第一個
     * @param t
     * @return
     */
    public boolean addFirst(T t);

    /**
     * 獲取第一個
     * @return
     */
    public T getFirst();

    /**
     * 添加到最后
     * @param t
     * @return
     */
    public boolean addLast(T t);

    /**
     * 獲取最后一個元素
     * @return
     */
    public T getLast();

    /**
     * 添加默認添加到最后
     * @param t
     * @return
     */
    public boolean add(T t);

    /**
     * 添加到指定位置
     * @param index 索引
     * @param t 數據
     * @return
     */
    public boolean add(int index, T t);

    /**
     * 獲取指定位置的元素
     * @param index 索引
     * @return
     */
    public T get(int index);
    
    
    /**
     * 移除指定元素
     * @param index
     * @return
     */
    public T remove(int index);
    
    /**
     * 移除第一個
     * @return
     */
    public boolean removeFirst();
    /**
     * 移除最后一個
     * @return
     */
    public boolean removeLast();
    
    /**
     * 是否包含
     * @param object
     * @return
     */
    public boolean contains(Object object);
    
    /**
     * 獲取迭代器
     * @return
     */
    public MyIterator<T> iterator();
}

迭代器接口

package com.ghg.data_structure.link;

public interface MyIterator<T> {

    public boolean hasNext();
    
    public T next();
    
    public boolean hasPrevious();  

    public T previous();
}

實現

package com.ghg.data_structure.link;

import java.util.NoSuchElementException;

public class MyLinkedList<T> implements MyList<T> {

    private int size = 0;

    private Node<T> first;

    private Node<T> last;

    private int position = 0;

    public MyLinkedList() {
        this.first = null;
        this.last = null;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public int size() {
        return size;
    }

    public boolean addFirst(T t) {
        Node<T> f = first;

        Node<T> newNode = new Node<T>(t, null, first);

        first = newNode;

        if (f == null) {
            last = newNode;
        } else {
            f.pre = newNode;
        }
        size++;
        return true;
    }

    public T getFirst() {
        return first.data;
    }

    public boolean addLast(T t) {

        Node<T> l = last;
        Node<T> newNode = new Node<T>(t, l, null);
        last = newNode;
        if (l == null) {
            first = newNode;
        } else {
            l.next = newNode;
        }
        size++;
        return true;
    }

    public T getLast() {
        return last.data;
    }

    public boolean add(T t) {
        return addLast(t);
    }

    public boolean add(int index, T t) {
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("index : " + index + " size : " + size);
        }

        if (index == size) {
            return addLast(t);
        }

        Node<T> current = first;

        for (int i = 0; i < index; i++) {
            current = current.next;
        }

        Node<T> pre = current.pre;

        Node<T> newNode = new Node<T>(t, pre, current);

        current.pre = newNode;
        /**
         * 如果沒有前置元素說明是第一個
         */
        if (pre == null) {
            first = newNode;
        } else {
            pre.next = newNode;
        }

        size++;
        return true;
    }

    public T get(int index) {

        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException("index : " + index + " size : " + size);
        }

        Node<T> current = first;

        for (int i = 0; i < index; i++) {
            current = current.next;
        }
        return current.data;
    }

    @Override
    public String toString() {

        Node<T> current = first;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < size; i++) {

            sb.append(current);
            current = current.next;
        }
        return sb.toString();

    }

    public T remove(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException("index : " + index + " size : " + size);
        }

        Node<T> current = first;

        for (int i = 0; i < index; i++) {
            current = current.next;
        }
        /**
         * 獲取當前元素的前置也后置元素,將這2個元素相連接
         */
        final Node<T> next = current.next;
        final Node<T> prev = current.pre;

        if (prev == null) {
            first = next;
        } else {
            prev.next = next;
        }

        if (next == null) {
            last = prev;
        } else {
            next.pre = prev;
        }

        size--;
        return current.data;
    }

    /**
     * 移除第一個
     */
    public boolean removeFirst() {
        /**
         * 獲取第一個元素
         */
        Node<T> current = first;
        /**
         * 獲取第一個元素的下一個元素
         */
        Node<T> next = current.next;
        /**
         * 賦值
         */
        first = next;

        /**
         * 判斷下一個是不是空,如果為空就說明是最后一個,目前只有一個元素
         */
        if (next == null) {
            last = null;
        } else {
            // 前置設置為空,因為是第一個了
            next.pre = null;
        }
        size--;
        return true;
    }

    /**
     * 移除最后個
     */
    public boolean removeLast() {
        /**
         * 獲取最后一個元素
         */
        Node<T> current = last;
        /**
         * 獲取最后一個的前一個元素
         */
        Node<T> pre = current.pre;
        /**
         * 賦值
         */
        last = pre;

        /**
         * 判斷前置是不是空,如果為空說明第一個為NULL
         */
        if (pre == null) {
            first = null;
        } else {
            // 將最后一個元素的,后置設置為空
            pre.next = null;
        }

        size--;
        return true;
    }

    public boolean contains(Object object) {
        if (object == null) {
            return false;
        }
        int index = 0;
        for (Node<T> current = first; current.next != null; current = current.next) {
            if (object.equals(current.data)) {
                break;
            }
            index++;
        }
        System.out.println("contains  index:  " + index);
        return index > 0;
    }
/*
    *//**
     * 是否有更多
     *//*
    public boolean hasNext() {

        if (position < size) {
            return true;
        } else {
            position = 0;

            return false;
        }

    }

    *//**
     * 下一個元素
     *//*
    public T next() {

        if (!hasNext()) {
            throw new NoSuchElementException();
        }

        return get(position++);
    }*/

    public class MyInnerIterator<T> implements MyIterator<T> {

        private MyLinkedList<T> myLinkedList;
        /**
         * 游標
         */
        private int cursor = 0;

        public MyInnerIterator(MyLinkedList<T> linkedList) {
            this.myLinkedList = linkedList;
        }

        public boolean hasNext() {
            return cursor<size;
        }

        public T next() {
            return myLinkedList.get(cursor++);
        }

        public boolean hasPrevious() {
            System.out.println("cursor  "+cursor);
            return cursor>0;
        }

        public T previous() {
            return myLinkedList.get(--cursor);
        }

    }

    /**
     * 獲取迭代器
     */
    public MyIterator<T> iterator() {
        return new MyInnerIterator<T>(this);
    }

}

測試

package com.ghg.data_structure.link;

public class MyListTest1 {

    public static void main(String[] args) {

        MyLinkedList<Integer> myLinkedList = new MyLinkedList<Integer>();

        myLinkedList.addFirst(3);

        myLinkedList.addFirst(5);

        System.out.println("\n 全部: " + myLinkedList.toString());

        System.out.println("\n 獲取第一個: " + myLinkedList.getFirst());
        System.out.println("\n 獲取最后一個: " + myLinkedList.getLast());

        myLinkedList.addLast(9);

        myLinkedList.addLast(-1);
        System.out.println("\n 全部: " + myLinkedList.toString());
        System.out.println("\n size : " + myLinkedList.size());

        myLinkedList.addFirst(67);

        System.out.println("\n 全部: " + myLinkedList.toString());

        System.out.println("\n index : " + myLinkedList.get(1));

        myLinkedList.add(45);
        myLinkedList.add(-80);
        System.out.println("\n 全部: " + myLinkedList.toString());

        myLinkedList.add(0, 45);
        System.out.println("\n 全部: " + myLinkedList.toString());

        myLinkedList.add(8, 43);
        System.out.println("\n 全部: " + myLinkedList.toString());

        myLinkedList.add(1, 33);
        myLinkedList.add(6, 12345);
        myLinkedList.add(11, 77);
        System.out.println("\n 全部: " + myLinkedList.toString());

        myLinkedList.removeFirst();
        myLinkedList.removeFirst();
        System.out.println("\n 全部: " + myLinkedList.toString());

        System.out.println("\n size: " + myLinkedList.size());

        myLinkedList.removeLast();
        myLinkedList.removeLast();
        System.out.println("\n 全部: " + myLinkedList.toString());

        System.out.println("\n size: " + myLinkedList.size());

        System.out.println("remove :" + myLinkedList.remove(3));
        System.out.println("\n 全部: " + myLinkedList.toString());

        System.out.println("\n size: " + myLinkedList.size());
        System.out.println("\n 全部: " + myLinkedList.toString());

        System.out.println("\n contains: " + myLinkedList.contains(3));
        
        System.out.println("get "+myLinkedList.get(6));
        /*System.out.println("\n 全部: " + myLinkedList.hasNext());
        System.out.println("\n while ");
        while(myLinkedList.hasNext()){
            System.out.print(myLinkedList.next()+" \t");
        }*/
        
        
        //System.out.println("\n 全部: " + myLinkedList.hasNext());
        
        System.out.println("\n 全部: iterator================ " );
        
        MyIterator<Integer> iterator = myLinkedList.iterator();
        while(iterator.hasNext()){
            System.out.print(iterator.next()+" \t");
        }
        
        MyIterator<Integer> iterator1 = myLinkedList.iterator();
        //System.out.println("\n hasnext:   "+iterator1.hasNext()+" size "+myLinkedList.size());
        
        System.out.println("\n next : "+iterator1.next());
        System.out.println("next : "+iterator1.next());
        System.out.println("hasPrevious : "+iterator1.hasPrevious());
        System.out.println("previous :"+iterator1.previous());
    }

}

image.png
image.png
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,702評論 6 534
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,615評論 3 419
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事?!?“怎么了?”我有些...
    開封第一講書人閱讀 176,606評論 0 376
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,044評論 1 314
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,826評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,227評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,307評論 3 442
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,447評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,992評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,807評論 3 355
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,001評論 1 370
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,550評論 5 361
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,243評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,667評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,930評論 1 287
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,709評論 3 393
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,996評論 2 374

推薦閱讀更多精彩內容