LinkedList-循环不工作-Java

LinkedList-循环不工作-Java,java,linked-list,counter,extend,Java,Linked List,Counter,Extend,我需要编写一个方法,返回一个数字——在链表中找到元素的次数。到目前为止,我有 package Question4; import net.datastructures.Node; public class SLinkedListExtended<E> extends SLinkedList<E> { // returns the number of occurrences of the given element in the list public

我需要编写一个方法,返回一个数字——在链表中找到元素的次数。到目前为止,我有

package Question4;

import net.datastructures.Node;

public class SLinkedListExtended<E> extends SLinkedList<E> {
    // returns the number of occurrences of the given element in the list
    public int count(E elem) {

        Node<E> cursor = tail;
    int counter = 0;

    if ((cursor != null) && (!(cursor.getElement().equals(elem)))) { //tail isnt null and element is not equal to elem 

        cursor = cursor.getNext(); //go to next node

    } else if ((cursor != null) && (cursor.getElement().equals(elem))){ //cursor isn't null and element equals elem

        counter++; //increment counter
    }
    else { 
        return counter; //return counter 
    }
    return counter;
}


public static void main(String[] args) {

    SLinkedListExtended<String> x = new SLinkedListExtended<String>();

    x.insertAtTail("abc");
    x.insertAtTail("def");
    x.insertAtTail("def");
    x.insertAtTail("xyz");
    System.out.println(x.count("def")); // should print "2"
    x.insertAtTail(null);
    x.insertAtTail("def");
    x.insertAtTail(null);
    System.out.println(x.count("def")); // should print "3"
    System.out.println(x.count(null)); // should print "2"
}
}
package问题4;
导入net.datastructures.Node;
公共类SLINKEDLISTENDED扩展SLinkedList{
//返回列表中给定元素的出现次数
公共整数计数(E元素){
节点光标=尾部;
int计数器=0;
如果((cursor!=null)&&(!(cursor.getElement().equals(elem)){//tail不为null且元素不等于elem
cursor=cursor.getNext();//转到下一个节点
}else如果((cursor!=null)&&(cursor.getElement().equals(elem)){//cursor不为null且元素等于elem
计数器+++;//递增计数器
}
否则{
返回计数器;//返回计数器
}
返回计数器;
}
公共静态void main(字符串[]args){
SLINKEDLISTEXTEND x=新的SLINKEDLISTEXTEND();
x、 插入附件(“abc”);
x、 插入附件(“def”);
x、 插入附件(“def”);
x、 插入附件(“xyz”);
System.out.println(x.count(“def”);//应打印“2”
x、 插入附件(空);
x、 插入附件(“def”);
x、 插入附件(空);
System.out.println(x.count(“def”);//应打印“3”
System.out.println(x.count(null));//应打印“2”
}
}
我已经扩展到一个正确编译的类,所以我知道问题出在我的方法中。我不知道该怎么办,我的代码返回0,这可能是保持在0的计数器整数,不经过loop语句。欢迎提出任何意见

编辑。SLinkedList代码:

import net.datastructures.Node;

public class SLinkedList<E> {
protected Node<E> head; // head node of the list
protected Node<E> tail; // tail node of the list (if needed)
protected long size; // number of nodes in the list (if needed)

// default constructor that creates an empty list
public SLinkedList() {
    head = null;
    tail = null;
    size = 0;
}

// update and search methods
public void insertAtHead(E element) {
    head = new Node<E>(element, head);
    size++;
    if (size == 1) {
        tail = head;
    }
}

public void insertAtTail(E element) {
    Node<E> newNode = new Node<E>(element, null);
    if (head != null) {
        tail.setNext(newNode);
    } else {
        head = newNode;
    }
    tail = newNode;
    size++;
}

public static void main(String[] args) { // test
    SLinkedList<String> list = new SLinkedList<String>();

    list.insertAtHead("lol");

}
导入net.datastructures.Node;
公共类链接列表{
受保护的节点头;//列表的头节点
受保护的节点尾部;//列表的尾部节点(如果需要)
受保护的长大小;//列表中的节点数(如果需要)
//创建空列表的默认构造函数
公共链接列表(){
head=null;
tail=null;
尺寸=0;
}
//更新和搜索方法
公共空白插入符(E元素){
head=新节点(元素,head);
大小++;
如果(大小==1){
尾=头;
}
}
公共无效插入附件(E元素){
Node newNode=新节点(元素,空);
if(head!=null){
tail.setNext(newNode);
}否则{
头=新节点;
}
tail=newNode;
大小++;
}
公共静态void main(字符串[]args){//test
SLinkedList list=新SLinkedList();
列表。插入日期(“lol”);
}

}count中的代码不在循环中,因此它将在第一个元素之后返回

试试这个:

public int count(E elem) {
    Node<E> cursor = tail;
    int counter = 0;
    while (true)
    {
        if ((cursor != null) && (!(cursor.getElement().equals(elem)))) { //tail isnt null and element is not equal to elem 
            cursor = cursor.getNext(); //go to next node
        } else if ((cursor != null) && (cursor.getElement().equals(elem))){ //cursor isn't null and element equals elem
            counter++; //increment counter
        }
        else { 
            return counter; //return counter 
        }
    }
}

另外,假定
节点游标=尾部
使其指向列表的末尾,您可能希望
节点游标=头部

也许您应该使用while循环而不是if子句

**while** ((cursor != null) && (!(cursor.getElement().equals(elem)))) {

您缺少的一个基本要素是循环。由于您本质上是在搜索某个内容,因此您希望遍历整个列表。一旦遇到与正在搜索的元素相匹配的元素,就需要将计数增加1。完成对整个列表的循环后,您希望返回该计数。这就是我的解决方案。我将其保持简单,以便您能够理解:

import java.util.LinkedList;

public class Duplicates<E> extends LinkedList<E> {

    public static void main(String[] args) {
        Duplicates<String> duplicates = new Duplicates<String>();
        duplicates.add("abc");
        duplicates.add("def");
        duplicates.add("def");
        duplicates.add("xyz");
        System.out.println(duplicates.duplicateCount("def"));
        duplicates.add(null);
        duplicates.add("def");
        duplicates.add(null);
        System.out.println(duplicates.duplicateCount("def"));
        System.out.println(duplicates.duplicateCount(null));
    }

    public int duplicateCount(E element) {
        int count = 0;
        for (E e : this) {
            if (e == element) {
                count++;
            }
        }
        return count;
    }
}

我建议你将Martin的答案(它告诉你如何计算元素)与这个结合起来,它告诉你如何使用foreach-你只需要将你的
链接到扩展的
实现
可伸缩的
,这应该是以下几点(您可以在
SLinkedList
上执行此操作,但我假设您被告知不要更改该列表的代码):

公共类SlinkedListended扩展SLinkedList实现了Iterable(){
公共迭代器迭代器(){
最终节点i头部=头部;
返回新的迭代器(){
节点电流=i头;
长位置=0;
公共布尔hasNext(){
返回当前值!=null&&position
我不能保证所有的细节,但这应该涵盖大部分内容。你也可以考虑使用<代码>等于而不是<代码>=,但是不要忘记检查元素是否无效。 只有当
hasNext
true
时,才应调用
next
,因此,如果它抛出异常(但它应该是一个
NoTouchElementException
,以与合同保持一致),则不成问题


实现
Iterable
使您的类与集合库兼容,因此支持foreach,但您可以通过调用
iterator
hasNext
next
自己来使用它进行原始迭代。

您有两个单独的问题需要解决:1.如何迭代列表(将取决于超类的实现)和2.如何计算元素(等于加上递增计数器)。OP使用的是自定义的
链接列表
,而不是Java的
链接列表
,因此也必须回答迭代问题(但问题中没有足够的数据来回答)。我假设自定义LinkedList实际上扩展了LinkedList,所以它仍然可以使用。我的方法应该仍然可以使用。因为这是一个赋值,我认为它不可能扩展
LinkedList
,但一切都是可能的。不,它的自定义:/不过感谢您的时间!如果您能够ost自定义
链接列表的代码。好的,我这样做了,但它仍然返回0。你能看到我的代码有什么错误吗?我看不到其他错误。D
import java.util.LinkedList;

public class Duplicates<E> extends LinkedList<E> {

    public static void main(String[] args) {
        Duplicates<String> duplicates = new Duplicates<String>();
        duplicates.add("abc");
        duplicates.add("def");
        duplicates.add("def");
        duplicates.add("xyz");
        System.out.println(duplicates.duplicateCount("def"));
        duplicates.add(null);
        duplicates.add("def");
        duplicates.add(null);
        System.out.println(duplicates.duplicateCount("def"));
        System.out.println(duplicates.duplicateCount(null));
    }

    public int duplicateCount(E element) {
        int count = 0;
        for (E e : this) {
            if (e == element) {
                count++;
            }
        }
        return count;
    }
}
2
3
2
public class SLinkedListExtended<E> extends SLinkedList<E> implements Iterable<E> () {

    public Iterator<E> iterator() {
        final Node<E> itHead = head;
        return new Iterator<E>() {

            Node<E> current = itHead;
            long position = 0;

            public boolean hasNext() {
                return current != null && position < size;
            }

            public E next() {
                current = current.getNext();
                ++position;
                return current.getElement();
            }

            public void remove() {
                throw new UnsupportedOperationException("Not supported yet.");
            }

        };
    }

};