如何在Java中使用单链表实现搜索功能?

How to implement Search Function using Singly Linked List in Java?

各位程序员大家好! 我想问一下如何使用Java(数据结构)在单链表中实现搜索功能。

问题:我程序的搜索功能只能访问元素的头部和尾部。 问题:如何访问所有元素?

示例代码:

import java.util.*;
public class MyLinkedList<T> {
    private Node<T> head;
    private Node<T> tail;

public void add(T element){
    Node<T> nd = new Node<T>();
    nd.setValue(element);
     if(head == null){
        head = nd;
        tail = nd;
      }
     else {
        tail.setNextRef(nd);
        tail = nd;
      }}
 public void delete(){
    if(head == null){
        System.out.println("List is empty...");
    }
    else{
    Node<T> tmp = head;
    head = tmp.getNextRef();
    if(head == null){
        tail = null;
    }
    System.out.println("Deleted: "+tmp.getValue());
    System.out.println("First Employee Name Deleted!");
    }
}
public void search(){
    Node<T> tmp = head;
        if(head==null){
            System.out.println("List is empty...");
        }
        else{
        String b=""+tmp.getValue();
        Scanner input=new Scanner(System.in);
        System.out.print("Enter an employee name to search: ");
        String search = input.nextLine();
        if(b.equals(search)){
         System.out.println("Found! "+tmp.getValue());
        }
        else if (b!=search){
            System.out.println("Not Found!");
        }
        tmp = tmp.getNextRef();
    }   }
  public void show(){
    Node<T> tmp = head;
    if(head==null){
        System.out.println("List is empty...");
    }
    else{
        while(true){
        if(tmp == null){
            break;
        }

        System.out.println(tmp.getValue());
        tmp = tmp.getNextRef();
    }}
}
public static void main(String a[]){
    MyLinkedList<String> sl = new MyLinkedList<String>();
    Scanner input = new Scanner(System.in);
    sl.add("Garcia, Bianca Axel, 001");
    sl.add("Temprosa, Camille Ann, 002");
    sl.add("Villanueva, Von Justin, 003");
    sl.add("Rivera, Reygie, 004");
    sl.add("Dapapac, Ronnelle, 005");
    sl.add("Bati, Aubrey, 006");
    sl.add("Fiestada, Diana Rose, 007");
    sl.add("Dobalada, Jojo, 008");
    sl.add("Del Mundo, Maria Ethel, 009");
    sl.add("Alejandro, Rachelle, 010");
    System.out.print("Welcome To Singly Linked List Management for Employee Names!\n(Created by: Alex del Rosario || Source Code: Mr. John Carlo Son)\n");
    while(true){
    System.out.println("*------------------------*");
    System.out.println("*PLEASE SELECT A FUNCTION*");
    System.out.println("*1.)Add Employee Name    *");
    System.out.println("*2.)Delete Employee Name *");
    System.out.println("*3.)Show Employee List   *");
    System.out.println("*4.)Search an Employee   *");
    System.out.println("*5.)Exit the program     *");
    System.out.println("*------------------------*");
    System.out.print("Enter a number: ");
    int select = input.nextInt();
    if(select==1){
    System.out.println("**Enter an employee name with ID number**");
    System.out.println("Use this format:(Last Name),(First Name),(ID number)");
    System.out.println("(ex. del Rosario, Alex, 0001)");
    System.out.print("Input here: ");
    input.nextLine();
    String employee=input.nextLine();
    sl.add(employee);
    System.out.println("Employee: "+employee+" successfully added!");
    }
    else if(select==2){
    sl.delete();
    }
    else if(select==3){
    System.out.println("Employee List:");
    sl.show();
    }
    else if(select==4){
    sl.search();
    }
    else if(select==5){
    System.out.println("*** THANK YOU FOR USING THIS PROGRAM! :) ***");
    System.exit(0);
    }
    else{
        System.out.println("INVALID INPUT!");
    }

    }}
}

class Node <T> implements Comparable<T> {

    private T value;
    private Node<T> nextRef;

    public T getValue() {
        return value;
    }
    public void setValue(T value) {
        this.value = value;
    }
    public Node<T> getNextRef() {
        return nextRef;
    }
    public void setNextRef(Node<T> ref) {
        this.nextRef = ref;
    }
    @Override
    public int compareTo(T arg) {
        if(arg == this.value){
            return 0;
        } else {
            return 1;
        }
    }
}

与其说是答案,不如说是小费。问问自己你想做什么。你是想使用Java提供的linked list还是自己写链表代码?

使用提供的列表迭代很容易。

private void search(String searchElement) {
     for (int i = 0; i < list.size(); i++) {
         String listElement = list.get(i);
         if (searchElement.equals(listElement)) {
             System.out.println("Found element " + searchElement + " at position " + i);
             return;
         }
     }
     System.out.println(searchElement + " does not appear in the list");
}

编写自己的列表时,您必须更加小心地使用列表。例如,您的 delete() 实现将不起作用。

public void delete(){
    if(head == null){
        System.out.println(List is empty...);
    }
    else{
       NodeAlex tmp = head;
       head = tmp.getNextRef();
       if(head == null){ // you need to check if head == tail or head.getNextRef() == null
          tail = null; // here you have to set tmp.setNextRef(null);
                       // and additionally define tmp as tail.
      }
      System.out.println(Deleted +tmp.getValue());
      System.out.println(First Employee Name Deleted!);
    }
}

编辑:要访问列表,您有两种可能性。首先你必须创建一个新实例,即(这里对于字符串,你可能想使用其他 types/objects)

List<String> list = new LinkedList<String>();

然后你基本上有两次机会在方法中访问列表。

(a) 您的方法与初始化列表的方法相同 class,但是,列表必须是全局字段。

private List<String> list;

private static void main(String[] args) {
     list = new LinkedList<String>();
     (...)
}

private static void search(String searchElement) {
     // has access on list
}

(b) 您只需将列表传递给所需的方法,如果该方法修改了列表,您需要再次 return 列表。

(main class, main method)
search(list, "Test");
list = delete(list, "Test");

(the class where the methods are located)
public void search(List<String> list, String searchElement) { ... }

public List<String> delete(List<String> list, String elementToDelete) {
      // delete element
      return list;
}