You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为LinkedListWithIterator的IteratorForLinkedList实现remove方法并验证代码

问题与代码验证

我在课程项目中需要为LinkedListWithIterator的内部类IteratorForLinkedList实现remove方法,要求新增额外数据字段,同时要包含接口定义、实现类及测试程序。我已经完成了代码编写,希望确认是否符合作业要求,以下是我的实现代码:

import java.util.Iterator;
import java.util.NoSuchElementException;
public class LinkedListWithIterator<T> implements ListWithIteratorInterface<T> {
    
    private Node firstNode;
    private int numberOfEntries;
    
    public LinkedListWithIterator() {
        initaliazeDataFields();
    }
    /**
     * Implementation for the ft list go here chapter 12, starting at 
     * segment 12.7
     * @return
     */
    public void clear() {
        initaliazeDataFields();
    }
    
    private void initaliazeDataFields() {
        firstNode = null;
        numberOfEntries = 0;
    }
    
    private Node getNodeAt(int givenPosition) {
        Node currentNode = firstNode;
        for (int counter = 1; counter < givenPosition; counter++)
            currentNode = currentNode.getNextNode;
        
        return currentNode;
    }
    
    public void add(T newEntry) {
        Node newNode = new Node(newEntry);
        
        if (isEmpty())
            firstNode = newNode;
        else {
            Node lastNode = getNodeAt(numberOfEntries);
            lastNode.setNextNode(newNode);
        }
        numberOfEntries++;
    }
    
    public void add(int givenPosition, T newEntry) {
        if ((givenPosition >= 1) && (givenPosition <= numberOfEntries + 1)) {
            Node newNode = new Node(newEntry);
            
            if(givenPosition == 1) {
                newNode.setNextNode(firstNode);
                firstNode = newNode;
            } else {
                Node nodeBefore = getNodeAt(givenPosition - 1);
                Node nodeAfter = nodeBefore.getNextNode();
                newNode.setNextNode(nodeAfter);
                nodeBefore.setNextNode(newNode);
            }
            numberOfEntries++;
        } else
            throw new IndexOutOfBoundsException("illegal position given to add operation");
    } // end add
    
    public boolean isEmpty() {
        boolean result;
        if (numberOfEntries == 0) {
            result = true;
        } else {
            result = false;
        } 
        return result;
    }
    
    public T[] toArray() {
        @SuppressWarnings("unchecked")
        T[] result = (T[])new Object[numberOfEntries];
        
        int index = 0;
        Node currentNode = firstNode;
        while ((index < numberOfEntries) && (currentNode != null)) {
            result[index] = currentNode.getData();
            currentNode = currentNode.getNextNode();
            index++;
        }
        return result;
    } // end to array
    
    
    
    public T remove(int givenPosition) {
        T result = null;
        if((givenPosition >= 1) && (givenPosition <= numberOfEntries)) {
            if (givenPosition == 1) {
                result = firstNode.getData();
                firstNode = firstNode.getNextNode();
            } else {
                Node nodeBefore = getNodeAt(givenPosition - 1);
                Node nodeToRemove = nodeBefore.getNextNode();
                result = nodeToRemove.getData();
                Node nodeAfter = nodeToRemove.getNextNode();
                nodeBefore.setNextNode(nodeAfter);
            }
            numberOfEntries--;
            return result;
            
        } else {
            throw new IndexOutOfBoundsException("illegal position given to remove ");
        }
    } // end remove
    
    public T replace(int givenPosition, T newEntry) {
        if((givenPosition >= 1) && (givenPosition <= numberOfEntries)) {
            Node desiredNode = getNodeAt(givenPosition);
            T originalEntry = desiredNode.getData();
            return originalEntry;
        }
        else
            throw new IndexOutOfBoundsException("Illegal Position given for replace method ");
    } // end replace
    
    public T getEntry(int givenPosition) {
        if ((givenPosition >= 1) && (givenPosition <= numberOfEntries)) {
            return getNodeAt(givenPosition).getData;
        } 
        else 
            throw new IndexOutOfBoundsException("Illegal Position given for getentry method ");
    } // end get entry
    
    public boolean contains(T anEntry) {
        boolean found = false;
        Node currentNode = firstNode;
        
        while(!found && (currentNode != null)) {
            if(anEntry.equals(currentNode.getData())) {
                found = true;
            } else {
                currentNode = currentNode.getNextNode;
            }
            
        }
        return found;
    }
    
    
    
    public Iterator<T> iterator() {
        return new IteratorForLinkedList();
    }
    
    public Iterator getIterator() {
        return iterator();
    }
    
    private class IteratorForLinkedList implements Iterator<T> {
        private Node nextNode;
        
        private IteratorForLinkedList() {
            nextNode = firstNode;
        }
        
        public T next() {
            T result;
            if (hasNext()) {
                result = nextNode.getData;
            } else {
                throw new NoSuchElementException("Illegal call to next(); iterator is after end of list");
            }
            return result;
        }
        
        public boolean hasNext() {
            return nextNode != null;
        }
        
        public void remove() {
            throw new UnsupportedOperationException("Remove() is not supported by this operator");
        }
    }
    
    // Implementation for private class node
    
    private class Node 
    {
        public T getData;
        public LinkedListWithIterator<T>.Node getNextNode;
        private T data;
        private Node next;
        
        private Node(T dataPortion) {
            this(dataPortion, null);
        }
        
        private Node(T dataPortion, Node nextNode) {
            data = dataPortion;
            next = nextNode;    
        }
        
        private T getData() {
            return data;
        }
        
        private void setData(T newEntry) {
            data = newEntry;
        }
        
        private Node getNextNode() {
            return next;
        }
        
        private void setNextNode(Node nextNode) {
            next = nextNode;
        }
    } // end node class
    
}

代码问题分析

你的代码目前不符合作业要求,主要问题如下:

  • IteratorForLinkedList的remove方法未实现:当前只是抛出UnsupportedOperationException,没有完成删除逻辑,也未新增必要的额外字段
  • 语法错误:多处方法调用漏写括号,比如currentNode.getNextNode、nextNode.getData应改为currentNode.getNextNode()、nextNode.getData()
  • 冗余字段:Node类中定义的公共字段getData和getNextNode多余,应删除(已有对应私有方法)
  • 逻辑错误:replace方法未执行替换操作,仅返回原数据
  • 缺少接口定义:作业要求包含ListWithIteratorInterface接口,但代码中未提供

修正后的完整代码

1. 接口定义 ListWithIteratorInterface<T>

import java.util.Iterator;

public interface ListWithIteratorInterface<T> {
    void clear();
    void add(T newEntry);
    void add(int givenPosition, T newEntry);
    T remove(int givenPosition);
    T replace(int givenPosition, T newEntry);
    T getEntry(int givenPosition);
    boolean contains(T anEntry);
    T[] toArray();
    boolean isEmpty();
    int getLength();
    Iterator<T> iterator();
    Iterator<T> getIterator();
}

2. 修正后的LinkedListWithIterator<T>实现类

import java.util.Iterator;
import java.util.NoSuchElementException;

public class LinkedListWithIterator<T> implements ListWithIteratorInterface<T> {
    private Node firstNode;
    private int numberOfEntries;

    public LinkedListWithIterator() {
        initializeDataFields();
    }

    @Override
    public void clear() {
        initializeDataFields();
    }

    private void initializeDataFields() {
        firstNode = null;
        numberOfEntries = 0;
    }

    private Node getNodeAt(int givenPosition) {
        Node currentNode = firstNode;
        for (int counter = 1; counter < givenPosition; counter++) {
            currentNode = currentNode.getNextNode();
        }
        return currentNode;
    }

    @Override
    public void add(T newEntry) {
        Node newNode = new Node(newEntry);
        if (isEmpty()) {
            firstNode = newNode;
        } else {
            Node lastNode = getNodeAt(numberOfEntries);
            lastNode.setNextNode(newNode);
        }
        numberOfEntries++;
    }

    @Override
    public void add(int givenPosition, T newEntry) {
        if ((givenPosition >= 1) && (givenPosition <= numberOfEntries + 1)) {
            Node newNode = new Node(newEntry);
            if (givenPosition == 1) {
                newNode.setNextNode(firstNode);
                firstNode = newNode;
            } else {
                Node nodeBefore = getNodeAt(givenPosition - 1);
                Node nodeAfter = nodeBefore.getNextNode();
                newNode.setNextNode(nodeAfter);
                nodeBefore.setNextNode(newNode);
            }
            numberOfEntries++;
        } else {
            throw new IndexOutOfBoundsException("非法位置:add操作");
        }
    }

    @Override
    public boolean isEmpty() {
        return numberOfEntries == 0;
    }

    @Override
    public int getLength() {
        return numberOfEntries;
    }

    @Override
    public T[] toArray() {
        @SuppressWarnings("unchecked")
        T[] result = (T[]) new Object[numberOfEntries];
        int index = 0;
        Node currentNode = firstNode;
        while (index < numberOfEntries && currentNode != null) {
            result[index] = currentNode.getData();
            currentNode = currentNode.getNextNode();
            index++;
        }
        return result;
    }

    @Override
    public T remove(int givenPosition) {
        T result = null;
        if ((givenPosition >= 1) && (givenPosition <= numberOfEntries)) {
            if (givenPosition == 1) {
                result = firstNode.getData();
                firstNode = firstNode.getNextNode();
            } else {
                Node nodeBefore = getNodeAt(givenPosition - 1);
                Node nodeToRemove = nodeBefore.getNextNode();
                result = nodeToRemove.getData();
                Node nodeAfter = nodeToRemove.getNextNode();
                nodeBefore.setNextNode(nodeAfter);
            }
            numberOfEntries--;
            return result;
        } else {
            throw new IndexOutOfBoundsException("非法位置:remove操作");
        }
    }

    @Override
    public T replace(int givenPosition, T newEntry) {
        if ((givenPosition >= 1) && (givenPosition <= numberOfEntries)) {
            Node desiredNode = getNodeAt(givenPosition);
            T originalEntry = desiredNode.getData();
            desiredNode.setData(newEntry);
            return originalEntry;
        } else {
            throw new IndexOutOfBoundsException("非法位置:replace操作");
        }
    }

    @Override
    public T getEntry(int givenPosition) {
        if ((givenPosition >= 1) && (givenPosition <= numberOfEntries)) {
            return getNodeAt(givenPosition).getData();
        } else {
            throw new IndexOutOfBoundsException("非法位置:getEntry操作");
        }
    }

    @Override
    public boolean contains(T anEntry) {
        boolean found = false;
        Node currentNode = firstNode;
        while (!found && currentNode != null) {
            if (anEntry.equals(currentNode.getData())) {
                found = true;
            } else {
                currentNode = currentNode.getNextNode();
            }
        }
        return found;
    }

    @Override
    public Iterator<T> iterator() {
        return new IteratorForLinkedList();
    }

    @Override
    public Iterator<T> getIterator() {
        return iterator();
    }

    // 实现了remove方法的迭代器内部类,新增了必要字段
    private class IteratorForLinkedList implements Iterator<T> {
        private Node nextNode;
        private Node lastReturnedNode; // 记录上一次next()返回的节点
        private boolean canRemove;     // 标记是否允许调用remove()

        private IteratorForLinkedList() {
            nextNode = firstNode;
            lastReturnedNode = null;
            canRemove = false;
        }

        @Override
        public T next() {
            if (!hasNext()) {
                throw new NoSuchElementException("调用next()非法:迭代器已到达列表末尾");
            }
            lastReturnedNode = nextNode;
            nextNode = nextNode.getNextNode();
            canRemove = true;
            return lastReturnedNode.getData();
        }

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

        @Override
        public void remove() {
            if (!canRemove) {
                throw new IllegalStateException("调用remove()非法:未先调用next()或已连续调用remove()");
            }
            // 删除lastReturnedNode节点
            if (lastReturnedNode == firstNode) {
                firstNode = firstNode.getNextNode();
            } else {
                Node nodeBefore = getNodeBefore(lastReturnedNode);
                nodeBefore.setNextNode(lastReturnedNode.getNextNode());
            }
            numberOfEntries--;
            lastReturnedNode = null;
            canRemove = false;
        }

        // 辅助方法:找到目标节点的前一个节点
        private Node getNodeBefore(Node targetNode) {
            Node currentNode = firstNode;
            while (currentNode != null && currentNode.getNextNode() != targetNode) {
                currentNode = currentNode.getNextNode();
            }
            return currentNode;
        }
    }

    // 修正后的Node类,删除冗余字段
    private class Node {
        private T data;
        private Node next;

        private Node(T dataPortion) {
            this(dataPortion, null);
        }

        private Node(T dataPortion, Node nextNode) {
            data = dataPortion;
            next = nextNode;
        }

        private T getData() {
            return data;
        }

        private void setData(T newEntry) {
            data = newEntry;
        }

        private Node getNextNode() {
            return next;
        }

        private void setNextNode(Node nextNode) {
            next = nextNode;
        }
    }
}

3. 测试程序 LinkedListIteratorTest.java

public class LinkedListIteratorTest {
    public static void main(String[] args) {
        LinkedListWithIterator<String> list = new LinkedListWithIterator<>();
        list.add("A");
        list.add("B");
        list.add("C");
        list.add("D");

        System.out.println("初始列表:");
        printList(list);

        // 测试迭代器remove方法
        System.out.println("\n使用迭代器删除元素B:");
        var iterator = list.iterator();
        while (iterator.hasNext()) {
            String element = iterator.next();
            if (element.equals("B")) {
                iterator.remove();
                break;
            }
        }
        printList(list);

        // 测试连续调用remove的异常
        System.out.println("\n测试连续调用remove():");
        try {
            iterator.remove();
        } catch (IllegalStateException e) {
            System.out.println("捕获到异常:" + e.getMessage());
        }

        // 测试删除第一个元素
        System.out.println("\n使用迭代器删除第一个元素:");
        iterator = list.iterator();
        iterator.next();
        iterator.remove();
        printList(list);
    }

    private static void printList(LinkedListWithIterator<String> list) {
        for (String element : list) {
            System.out.print(element + " ");
        }
        System.out.println();
    }
}

修正说明

  1. 迭代器remove方法实现:新增lastReturnedNode(记录上一次next()返回的节点)和canRemove(标记是否允许调用remove)两个字段,符合作业要求的新增额外数据字段
  2. 修复语法错误:补全所有方法调用的括号
  3. 删除冗余字段:移除Node类中多余的公共字段
  4. 修正逻辑错误:完善replace方法的替换逻辑
  5. 补充接口定义:添加作业要求的ListWithIteratorInterface接口
  6. 符合Iterator规范:实现remove方法的约束:必须先调用next()才能调用remove(),且不能连续调用

内容的提问来源于stack exchange,提问作者Brandon Eisgruber

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 19:55:22