データ構造の復習-単一チェーンテーブル

11142 ワード

時間を割いて復習し、実戦したデータ構造-単一チェーンテーブルを記録します.
package com.dev.dontworry;

/**
 * Created by     on 2018/2/5.
 */

public class MyLinkedList {
    private Node head;
    private int size = 0;

    public int size(){
       return size;
    }

    static class Node{
        private int data;
        private Node next;
        public Node(int data){
            this.data = data;
        }

        public Node next(){
            return next;
        }

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

    public boolean add(Node newNode){
        if(newNode == null){
            return false;
        }
        if(head == null){
            head = newNode;
        }else {
            Node tmp = head;
            while (tmp.next() != null) {
                tmp = tmp.next();
            }
            tmp.setNext(newNode);
        }
        size++;
        return true;
    }

    public boolean add(Node newNode, int position){
        if(newNode == null || position < 1 || position > size){
            return false;
        }
        if(head == null){
            head = newNode;
        }else {
            Node tmp = head;
            int count = 1;
            if (position == 1) {
                newNode.setNext(tmp);
                head = newNode;
                size++;
                return true;
            }
            while (count < position - 1) {
                count++;
                tmp = tmp.next();
            }
            newNode.setNext(tmp.next());
            tmp.setNext(newNode);
        }
        size++;
        return true;
    }

    public boolean remove(int position){
        if(position < 1 || position > size){
            return false;
        }
        int count = 1;
        Node tmp = head;
        if(position == 1){
            head = tmp.next();
            tmp.setNext(null);
            size--;
            return true;
        }
        while(count < position - 1){
            count++;
            tmp = tmp.next();
        }
        tmp.setNext(tmp.next().next());
        size--;
        return true;
    }

    @Override
    public String toString() {
        String info = "size = " + size + ",[";
        Node tmp = head;
        while(tmp != null){
            if(tmp.next() != null) {
                info += tmp.data + " -> ";
                tmp = tmp.next();
            }else{
                info += tmp.data;
                break;
            }
        }
        info += "]";
        return info;
    }

    public static void main(String[] args){
        MyLinkedList linkedList = new MyLinkedList();
        linkedList.add(new Node(3));
        linkedList.add(new Node(4));
        linkedList.add(new Node(7));
        linkedList.add(new Node(2));
        linkedList.add(new Node(1), 1);
        linkedList.add(new Node(5));
        linkedList.remove(1);
        System.out.println(linkedList.toString());
    }
}