【发布时间】:2019-11-23 08:41:16
【问题描述】:
这是我创建的链接类,我编写了一个方法来检查我的链接列表中是否有重复的单词。我试图将字符串发送到 addFirst 方法,但我不知道为什么它对我不起作用
class LinkedList<String>
{
private class Node<String>
{
private String word; // reference to the element stored at this node
private Node<String> next; // reference to the subsequent node in the list
public Node(String w, Node<String> n)
{
word = w;
next = n;
}
public String getWord( ) { return word; }
public Node<String> getNext( ) { return next; }
public void setNext(Node<String> n) { next = n; }
}
private Node<String> head = null; // head node of the list (or null if empty)
private Node<String> tail = null; // last node of the list (or null if empty)
private int size = 0; // number of nodes in the list
public LinkedList( ) { }
public int size( ) { return size; }
public boolean isEmpty( ) { return size == 0; }
public Node<String> getHead( )
{ // returns the head node
if (isEmpty( )) return null;
return head;
}
public void addFirst(Node<String> w)
{ Node<String> newest;
newest= w;
tail.next=newest;
newest.next=head;
size++;
}
public void addLast(Node<String> w){
Node<String> newest;
newest=w;
tail.next=newest;
newest.next=head;
size++;
}
public String last( )
{ // returns (but does not remove) the last element
if (isEmpty( )) return null;
return tail.getWord( );
}
public boolean checkDuplicate(Node<String> w) {
Node temp;
for(Node a=tail.next;a !=null;a=a.next){
temp=a;
for(Node b=temp.next;b != null;b=b.next){
if(b.equals(temp.next))
return true;
}
}
return false;
}
}
主要是我无法将单词插入循环链表
public class Duplicate {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
LinkedList<String> list = new LinkedList<String>();
// the prblem start from here
list.addFirst("world");
list.addFirst("world");
list.addFirst("will");
list.addFirst("be");
list.addFirst("will");
list.addFirst("a better");
list.addFirst("place");
//to here
System.out.println(list.checkDuplicate(list.getHead()));
}
}
【问题讨论】:
-
您的 addFirst 方法接受的是节点对象,而不是字符串。
标签: java string methods circular-dependency