java黑皮书24.2----(在MyLinkedList中实现操作)


问题描述

实现contains(E e), get(int index), indexOf(E e), lastIndexOf(E e)和set(int index, E e)方法


难点分析:

提示:其实也可以去看源码:

public boolean contains(Object o)判断是否含有某一元素。
public E get(int index)返回指定位置的元素。
public int indexOf(Object o)查找指定元素从前往后第一次出现的索引。
public int lastIndexOf(Object o)查找指定元素最后一次出现的索引。
public E set(int index, E element)设置指定位置的元素。

代码:

提示:这主要主要size这个数据域,不想用数组实现线性表,这个实现线性表有点容易忘记size这个数据域;

import java.util.*;

public class Lab24_2 {
    public static void main(String[] args) {
        new Lab24_2();
    }

    public Lab24_2() {
        String[] names = {"Tom", "Susan", "Kim", "George", "Peter",
                "Jean", "George", "Jane", "Denise", "Jenny", "Susan", "Kathy", "Jane"};
        MyList<String> list = new MyLinkedListExtra<>(names);

        System.out.println(list);
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a name: ");
        String name = input.next();

        System.out.print("Enter an index: ");
        int index = input.nextInt();

        System.out.println(name + " is in the list? " + list.contains(name));
        System.out.println("name at index " + index + " is " + list.get(index));

        System.out.println(name + " is at index " + list.indexOf(name));
        System.out.println(name + " is at last index " + list.lastIndexOf(name));

        list.set(index, name);
        //这个是为了检测set方法是否成功实现
//        System.out.println(list);
    }
}

class MyLinkedListExtra<E> extends MyLinkedList<E> {

    /**
     * Create an empty list
     */
    public MyLinkedListExtra() {

    }

    /**
     * Create a list from an array of objects
     */
    public MyLinkedListExtra(E[] objects) {
        for (int i = 0; i < objects.length; i++)
            add(i, objects[i]);

    }

    @Override
    /** Return true if this list contains the element e */
    public boolean contains(Object o) {
        Node<E> temp = head;
        while (temp != null) {
            if (o.equals(temp.element))
                return true;
            temp = temp.next;
        }
        return false;
    }

    @Override
    /** Return the element from this list at the specified index */
    public E get(int index) {
        //这里其实可以写一个检测下标的方法,如果下标给的不好,直接抛出异常
        Node<E> temp = head;
        if (index == 0) {
            return head.element;
        } else if (index < size) {
            for (int i = 0; i < index; i++)
                temp = temp.next;

            return temp.element;
        }
        return null;
    }

    @Override
    /** Returns the index of the first matching element in this list.
     *  Returns -1 if no match. */
    public int indexOf(Object o) {
        Node<E> temp = head;
        for (int i = 0; i < size; i++) {
            if (o.equals(temp.element))
                return i;
            temp = temp.next;
        }

        return -1;
    }

    @Override
    /** Returns the index of the last matching element in this list
     *  Returns -1 if no match. */
    public int lastIndexOf(Object o) {
        int temp = -1;
        Node<E> current = head;
        for (int i = 0; i < size; i++) {
            if (o.equals(current.element))
                temp = i;

            current = current.next;
        }

        if (temp >= 0)
            return temp;

        return temp;
    }

    @Override
    /** Replace the element at the specified position in this list
     *  with the specified element. */
    public E set(int index, E e) {
        Node<E> temp = head;
        Node<E> son;
        for (int i = 1; i < index; i++)
            temp = temp.next;

        son = (temp.next).next;
        temp.next = new Node<>(e);
        (temp.next).next = son;
        return e;
    }
}

class MyLinkedList<E> implements MyList<E> {
    protected Node<E> head, tail;
    protected int size = 0;

    /**
     * Create a default list
     */
    public MyLinkedList() {
    }

    /**
     * Create a list from an array of objects
     */
    public MyLinkedList(E[] objects) {
//        super(objects);
        for (int i = 0; i < objects.length; i++)
            add(objects[i]);

    }

    /**
     * Return the head element in the list
     */
    public E getFirst() {
        if (size == 0) {
            return null;
        } else {
            return head.element;
        }
    }

    /**
     * Return the last element in the list
     */
    public E getLast() {
        if (size == 0) {
            return null;
        } else {
            return tail.element;
        }
    }

    /**
     * Add an element to the beginning of the list
     */
    public void addFirst(E e) {
        Node<E> newNode = new Node<E>(e); // Create a new node
        newNode.next = head; // link the new node with the head
        head = newNode; // head points to the new node
        size++; // Increase list size

        if (tail == null) // the new node is the only node in list
            tail = head;
    }

    /**
     * Add an element to the end of the list
     */
    public void addLast(E e) {
        Node<E> newNode = new Node<E>(e); // Create a new for element e

        if (tail == null) {
            head = tail = newNode; // The new node is the only node in list
        } else {
            tail.next = newNode; // Link the new with the last node
            tail = tail.next; // tail now points to the last node
        }

        size++; // Increase size
    }


    @Override
    /** Add a new element at the specified index
     * in this list. The index of the head element is 0 */
    public void add(int index, E e) {
        if (index == 0) {
            addFirst(e);
        } else if (index >= size) {
            addLast(e);
        } else {
            Node<E> current = head;
            for (int i = 1; i < index; i++) {
                current = current.next;
            }
            Node<E> temp = current.next;
            current.next = new Node<E>(e);
            (current.next).next = temp;
            size++;
        }
    }

    /**
     * Remove the head node and
     * return the object that is contained in the removed node.
     */
    public E removeFirst() {
        if (size == 0) {
            return null;
        } else {
            Node<E> temp = head;
            head = head.next;
            size--;
            if (head == null) {
                tail = null;
            }
            return temp.element;
        }
    }

    /**
     * Remove the last node and
     * return the object that is contained in the removed node.
     */
    public E removeLast() {
        if (size == 0) {
            return null;
        } else if (size == 1) {
            Node<E> temp = head;
            head = tail = null;
            size = 0;
            return temp.element;
        } else {
            Node<E> current = head;

            for (int i = 0; i < size - 2; i++) {
                current = current.next;
            }

            Node<E> temp = tail;
            tail = current;
            tail.next = null;
            size--;
            return temp.element;
        }
    }

    @Override
    /** Remove the element at the specified position in this
     *  list. Return the element that was removed from the list. */
    public E remove(int index) {
        if (index < 0 || index >= size) {
            return null;
        } else if (index == 0) {
            return removeFirst();
        } else if (index == size - 1) {
            return removeLast();
        } else {
            Node<E> previous = head;

            for (int i = 1; i < index; i++) {
                previous = previous.next;
            }

            Node<E> current = previous.next;
            previous.next = current.next;
            size--;
            return current.element;
        }
    }

    @Override
    public E set(int index, E e) {
        return null;
    }

    @Override
    /** Override toString() to return elements in the list */
    public String toString() {
        StringBuilder result = new StringBuilder("[");

        Node<E> current = head;
        for (int i = 0; i < size; i++) {
            result.append(current.element);
            current = current.next;
            if (current != null) {
                result.append(", "); // Separate two elements with a comma
            } else {
                result.append("]"); // Insert the closing ] in the string
            }
        }

        return result.toString();
    }

    @Override
    /** Clear the list */
    public void clear() {
        size = 0;
        head = tail = null;
    }


    @Override
    /** Return the element at the specified index */
    public E get(int index) {
        System.out.println("Implementation left as an exercise");
        return null;
    }

    @Override
    public int indexOf(Object e) {
        return 0;
    }

    @Override
    public int lastIndexOf(E e) {
        return 0;
    }

    @Override
    public int size() {
        return 0;
    }

    @Override
    public boolean isEmpty() {
        return false;
    }

    @Override
    public boolean contains(Object o) {
        return false;
    }

    @Override
    /** Override iterator() defined in Iterable */
    public java.util.Iterator<E> iterator() {
        return new LinkedListIterator();
    }

    @Override
    public Object[] toArray() {
        return new Object[0];
    }

    @Override
    public <T> T[] toArray(T[] a) {
        return null;
    }

    @Override
    public boolean add(E e) {
        return false;
    }

    @Override
    public boolean remove(Object o) {
        return false;
    }

    @Override
    public boolean containsAll(Collection<?> c) {
        return false;
    }

    @Override
    public boolean addAll(Collection<? extends E> c) {
        return false;
    }

    @Override
    public boolean removeAll(Collection<?> c) {
        return false;
    }

    @Override
    public boolean retainAll(Collection<?> c) {
        return false;
    }

    private void checkIndex(int index) {
        if (index < 0 || index >= size)
            throw new IndexOutOfBoundsException
                    ("Index: " + index + ", Size: " + size);
    }

    private class LinkedListIterator
            implements java.util.Iterator<E> {
        private Node<E> current = head; // Current index

        @Override
        public boolean hasNext() {
            return (current != null);
        }

        @Override
        public E next() {
            E e = current.element;
            current = current.next;
            return e;
        }

        @Override
        public void remove() {
            System.out.println("Implementation left as an exercise");
        }
    }

    protected static class Node<E> {
        E element;
        Node<E> next;

        public Node(E element) {
            this.element = element;
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值