我认为这很容易但我在从文本文件中搜索节点时遇到问题。
文本文件中的数据如下:
1
2
3
4
5
数据存储在字符串“word”中。它们是数字以避免复杂性。
问题是它在调用搜索方法时一直返回false。
public class Search
{
static int count; // number of elements
Search ()
{
count = 0;
}
static void inputdata (Node head, Node node) throws IOException
{
BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));
BufferedReader reader = new BufferedReader (new FileReader ("Words.txt"));
String word;
String line = null;
while ((line = reader.readLine ()) != null)
{
word = (line);
node = new Node (word);
node.next = head;
head = node; // need to set the new head of the list to the node that was just inserted
count++;
}
reader.close ();
node = head;
System.out.println ("Here is the list:");
System.out.println ();
do
{
System.out.println (node.data);
node = node.next;
}
while (node != null);
System.out.println ();
System.out.println ();
}
static boolean Found (String search, Node head, Node node) // recursive search method
{
boolean found;
Node temp; // sets a termpoary node to the head
node = head;
temp = head;
while (temp != null)
{
if (temp.data.equals (search))
return true;
temp = temp.next;
}
return false;
}
public static void main (String str[]) throws IOException
{
BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));
DecimalFormat df = new DecimalFormat ("#");
//Search list = new Search (); //calls list via constructor
Node head = null;
Node node = null;
inputdata (head, node);
System.out.println (count + " entries");
String search, repeat;
System.out.println ();
System.out.println ("Which word do you want to search within the linked list?"); // returns true/false from a method
search = stdin.readLine ();
System.out.println (Found (search, head, node));
}
}
其他文件(类):
public class Node
{
Node next, prev;
String data;
public Node (String data)
{
this.data = data;
}
}
答案 0 :(得分:0)
您的问题是您的链接列表一次只有一个对象,因为您总是将node.next设置为head,并且前往节点。因此,您将始终只打印相同的数字(我将猜测,正是您所看到的)。
您需要做的是修复插入例程。这样的事情应该做(请注意,它是未经测试的)
Node prev;
while((line = reader.readLine()) != null)
{
word = line;
node = new Node(word);
node.next = null;
if(head == null) {
head = node;
}
if(prev != null) {
prev.next = node;
}
prev = node;
}