链表list()方法。如何

时间:2013-11-04 07:06:48

标签: java

okey,我有一个链表(不是集合),我创建了一个新的方法来查找我的链表中的对象。所以像这样:

 public Object find(Linked obj) {

        Linked newObj = firstLink;

        while(newObj != null) {

            if(newObj == obj) {
                return obj;
            }
            else {

                newObj = newObj.next;
            }
        }

顺便说一下,我有 2个课程LinkedLinkedlist。在第一个中,我引用了下一个节点和显示功能。主要操作在Linkedlist中,我有所有方法,如insert,display和firstLink引用(最后一个)在我的列表中插入节点)(我的find()方法也在这个类中)。所以在我的主要功能中我这样做:

Linkedlist obj = new Linkedlist();
obj.insert("Auto");

Linkedlist obj2 = new Linkedlist();
obj2.insert("Moto");

如何调用我的方法find()来检查我的Linkedlist是否有(例如)obj2

2 个答案:

答案 0 :(得分:1)

这样想:

你有Linked类(这是一个链表节点,每个节点应该有下一个指针和节点内的元素)。所以这个类应该有构造函数,setter和getter方法。

另一方面,Linkedlist类是管理Linked对象(管理链表节点)的主类。在这个类中,您应该引用根节点(您插入的第一个节点)。因此,在您的程序中,您应该只有一个/多个Linked对象和Linkedlist作为主类。

Linked root = new Linked("Auto",null); //here Linked constructor takes 2 parameters, the element and the next pointer.
//Since you only inserted one element so far, the next element should be null.

//Insert another element
insertAtEnd("Moto");

public void insertAtEnd(String element){
    Linked curr = root;
    while(curr.next != null) curr = curr.next;
    curr.setNext(new Linked(element,null);
}

public Linked findElement(String element){
    Linked curr = root;
    while(curr!=null){
         if(curr.getElement().equals(element)) return curr;
         else curr = curr.next;
    }
    return null; //element not found
}

答案 1 :(得分:0)

  • 将LinkedList中的单个对象与另一个对象进行比较:

    equals()实施方法Linked。在此方法中,检查两个对象中包含的字符串(迭代中的当前对象和要查找的对象)是否相同。为此,您应该使用String.equals(String other)方法

  • 要比较两个LinkedLists,请编写另一个equals()方法。这次是LinkedList。在这种方法中你应该比较,例如两个列表中的元素数量。如果列表包含相同数量的元素,则可以使用先前定义的Linked.equals()逐项比较列表。