LeetCode算法学习笔记 - Day5

Java双链表的设计

public class Node {
    public int data;
    public Node prev;
    public Node next;
    public Node(){

    }

    public Node (int data){
        this.data = data;
    }
}
package Double_linked_list;

public class MyLinkedList {
    public Node head;

    public MyLinkedList(int i){
        head = new Node(i);
    }

    /**
     * 删除指定结点
     * @param index
     * @return
     */
    public boolean deleteAtIndex(int index){
        Node temp = head;
        int i = 0;
        while (temp.next != null){
            if (index == i){
                temp.prev.next = temp.next;
                temp.next.prev = temp.prev;
                return true;
            }
            temp = temp.next;
            i++;
        }
        return false;
    }

    /**
     * 在指定位置插入数据
     * @param index
     * @param data
     * @return
     */
    public Node addAtIndex(int index,int data){
        if (index <= 0){
            addAtHead(data);
            return head;
        }
        Node tempA = head;
        int i = 0;
        while (tempA.next != null){
            i++;
            tempA = tempA.next;
        }
        if (index > i){
            return null;
        }
        if (index == i){
            addAtTail(data);
            return head;
        }
        else {
            Node tempB =head;
            int j = 0;
            while (tempB.next != null){
                if (j == index){
                    Node node = new Node(data);
                    node.prev = tempB.prev;
                    node.next = tempB;
                    tempB.prev.next = node;
                    tempB.prev = node;
                    return node;
                }
                tempB = tempB.next;
                j++;
            }
        }
        return null;
    }

    /**
     * 修改头结点
     * @param data
     * @return
     */
    public Node addAtHead(int data){
        Node node = new Node(data);
        Node temp = head;
        temp.prev = node;
        node.next = temp;
        head = node;
        return head;
    }

    /**
     * 获取第index个元素
     * @param index
     * @return
     */
    public Node get(int index){
        Node temp = head;
        int i = 0;
        if (index == 0){
            return temp;
        }
        while (temp.next != null){
            temp = temp.next;
            i++;
            if (index == i){
                return temp;
            }
        }
        return null;
    }

    /**
     * 添加到结尾
     * @param data
     */
    public void addAtTail(int data){
        Node temp = head;
        while (temp.next != null){
            temp = temp.next;
        }
        Node node = new Node(data);
        node.prev = temp;
        temp.next = node;
    }

    public void print(){
        Node temp = head;
        while (temp != null){
            System.out.print(temp.data+",");
            temp = temp.next;
        }
        System.out.println();
    }
}

你可能感兴趣的:(leetcode,算法,职场和发展)