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

如何修改有序链表addOnce()方法避免重复并返回原节点?

问题描述

我需要实现有序链表的addOnce()方法,核心需求如下:

  • 若待添加元素与链表中已有节点通过compareTo()方法判定相等,返回链表中原有的节点,禁止添加新节点
  • 若链表中不存在相等元素,则将新节点按顺序插入链表,返回该新节点

但当前实现的addOnce()方法存在两个问题:

  1. 会重复添加相同元素,导致链表中出现重复节点
  2. 返回的不是首次添加的原节点,触发测试报错「Error: The initial item was not returned for XXX」,最终输出的链表不符合“无重复有序”的预期

测试代码(无需修改)

import java.util.Iterator;
public class OrderedListTest {
    static private class Courses implements Comparable<Courses>{
        String rubric;
        int number;
        int occurance;
        public Courses(String rub, int num, int occ) {
            rubric = rub;
            number = num;
            occurance = occ;
        }
        public int compareTo(Courses other) {
            if (rubric.compareTo(other.rubric) < 0)
                return -1;
            else if (rubric.compareTo(other.rubric) > 0)
                return 1;
            else
                return number - other.number;
        }
        public String toString() {
            return rubric + " " + number;
        }
    }
    public static void main(String[] args) {
        Courses listOfCourses[] = {
            new Courses("COSC", 2436, 1),
            new Courses("ITSE", 2409, 1),
            new Courses("COSC", 1436, 1),
            new Courses("ITSY", 1300, 1),
            new Courses("ITSY", 1300, 2),
            new Courses("COSC", 1436, 2),
            new Courses("COSC", 2436, 2),
            new Courses("ITSE", 2417, 1),
            new Courses("ITNW", 2309, 1),
            new Courses("CPMT", 1403, 1),
            new Courses("CPMT", 1403, 2)};
        OrderedAddOnce<Courses> orderedList = new OrderedAddOnce<Courses>();
        Courses result;
        for (int i = 0; i < listOfCourses.length; i++){
            result = orderedList.addOnce(listOfCourses[i]);
            if (result == null)
                System.out.println("Error: findOrAdd returned null for " + listOfCourses[i]);
            else {
                if (result.occurance != 1)
                    System.out.println("Error: The initial item was not returned for " + result);
                if (result.compareTo(listOfCourses[i]) != 0)
                    System.out.println("Error: " + listOfCourses[i] + " was passed to findOrAdd but " + result + " was returned");
            }
        }
        Iterator<Courses> classIter = orderedList.iterator();
        while(classIter.hasNext()) {
            System.out.println(classIter.next());
        }
        // 最终应该输出7个不重复的有序课程
    }
}

待调试代码(重点为addOnce()方法)

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

/**
* @author User
*/

// COSC 2436实验3和4的接口
/**
* @param <E> 有序列表中元素的类型
*/
interface AddOnce <E extends Comparable<? super E>> {
    /**
    * 该方法在列表中查找已添加的对象:
    * - 如果找到与当前对象通过compareTo()判定相等的对象,返回列表中已存在的对象
    * - 如果未找到,则将新对象按顺序添加到列表,返回新对象
    *
    * @param item 要查找并添加(若不存在)的对象
    *
    * @return 要么是传入的对象,要么是列表中已存在的相等对象
    */
    public E addOnce(E item);
}

// 泛型有序链表
public class OrderedAddOnce<E extends Comparable<? super E>> implements Iterable<E>, AddOnce<E> {
    private Node<E> firstNode;
    public OrderedAddOnce() {
        this.firstNode = null;
    }
    @Override
    public E addOnce(E item) {
        Node<E> current;
        if (firstNode == null || item.compareTo(firstNode.data) <= 0) {
            Node<E> newNode = new Node<>(item);
            newNode.next = firstNode;
            firstNode = newNode;
            return firstNode.data;
        }
        current = firstNode;
        while (current.next != null && item.compareTo(current.next.data) > 0) {
            current = current.next;
        }
        Node<E> newNode = new Node<>(item);
        newNode.next = current.next;
        current.next = newNode;

        return newNode.data;
    }
    @Override
    public Iterator<E> iterator() {
        return new AddOnceIterator();
    }
    private class AddOnceIterator implements Iterator<E> {
        private Node<E> currentNode = firstNode;

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

        @Override
        public E next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }
            E data = currentNode.data;
            currentNode = currentNode.next;
            return data;
        }
    }
    private class Node<E> {
        public E data;
        public Node<E> next;

        public Node(E initialData){
            this.data = initialData;
            this.next = null;
        }
    }
}

当前错误输出

Error: The initial item was not returned for ITSY 1300
Error: The initial item was not returned for COSC 1436
Error: The initial item was not returned for COSC 2436
Error: The initial item was not returned for CPMT 1403
COSC 1436
COSC 1436
COSC 2436
COSC 2436
CPMT 1403
CPMT 1403
ITNW 2309
ITSE 2409
ITSE 2417
ITSY 1300
ITSY 1300

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 01:37:05