编写单链表类(从头开始)- remove、indexOf 方法无法正常工作。

huangapple 未分类评论53阅读模式
英文:

Writing singly Linked List class from scratch - remove, indexOf methods not working

问题

我正在从头开始编写单向链表类但是在某些地方我的remove和likely indexOf方法不起作用

public E remove(int index){
    if(index < 0 || index > size-1)
        throw new IndexOutOfBoundsException("IndexOutOfBounds");

    if(index == 0) {
        E temp1 = head.data;
        Node temp2 = head.next;
        head.next = null;
        head = temp2;
        return temp1;
    }

    Node<E> hopper = getNode(index-1);
    Node<E> toRemove = hopper.next;

    E temp = toRemove.data;
    hopper.next = hopper.next.next;
    toRemove.data = null;
    toRemove.next = null;
    return temp;
}

对于remove方法我怀疑在某些情况下存在边缘案例或一些逻辑错误在我的JUnit测试器中它似乎根本没有删除任何内容至于indexOf方法

public int indexOf(Object o){
    if(o == null) {
        Node<E> hopper = head;
        for(int i = 0; i < size-1; i++) {
            if(hopper.data == o)
                return i;
            hopper = hopper.next;
    }}
    else {
        Node<E> hopper = head;
        for(int i = 0; i < size-1; i++) {
            if(hopper.data.equals(o))
                return i;
            hopper = hopper.next;
        }}
    return -1;
}

在我的JUnit测试器中contains方法不起作用而该方法实际上只是调用indexOf来执行搜索

如果需要我可以提供任何其他代码如果有人能够帮助解释我出错的地方我将非常感谢谢谢
英文:

I am writing the singly linked list class from scratch but somewhere my remove at an index and likely indexOf methods are not working.

	public E remove(int index){
	if(index &lt; 0 || index &gt; size-1)
		throw new IndexOutOfBoundsException(&quot;IndexOutOfBounds&quot;);
	
	if(index == 0) {
		E temp1 = head.data;
		Node temp2 = head.next;
		head.next = null;
		head = temp2;
		return temp1;
	}
	
	Node&lt;E&gt; hopper = getNode(index-1);
	Node&lt;E&gt; toRemove = hopper.next;
	
	E temp = toRemove.data;
	hopper.next = hopper.next.next;
	toRemove.data = null;
	toRemove.next = null;
	return temp;
}

For remove, I suspect there is a fringe case or some logical error somewhere. In my JUnit tester, it appears to not remove anything at all. And as for indexOf:

	public int indexOf(Object o){
	if(o == null) {
		Node&lt;E&gt; hopper = head;
		for(int i = 0; i &lt; size-1; i++) {
			if(hopper.data == o)
				return i;
			hopper = hopper.next;
	}}
	
	else {
		Node&lt;E&gt; hopper = head;
		for(int i = 0; i &lt; size-1; i++) {
			if(hopper.data.equals(o))
				return i;
			hopper = hopper.next;
			}}
		
	return -1;
}

In my JUnit tester, contains does not work and that method literally just calls indexOf to do the search.

I can provide any additional code if needed. If someone could help explain where I am going wrong, I would greatly appreciate it. Thanks!

huangapple
  • 本文由 发表于 2020年4月6日 01:01:58
  • 转载请务必保留本文链接:https://java.coder-hub.com/61046247.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定