单链表元素

singly linked list element

我正在制作一个程序,让用户可以添加整数元素,获取它的长度,并获取它的中间元素。我的问题是我不知道要获取中间元素要写什么。

 public int getLength()
{}

 public Node getMid() {}

 public void insert(int val)
{}

 public void display()
{}
   
public class SinglyLinkedList {
    
       public static void main(String[] args)
{             
    Scanner scan = new Scanner(System.in);
    LinkedList list = new LinkedList();         
    char ch;
    do
    {
        System.out.println("\nSingly Linked List\n");                     
        System.out.println("Enter integer element to insert:");
        list.insert( scan.nextInt() );       
        System.out.println("Length of the Linked List: "+ list.getLength() );      
        list.display();            
        System.out.println("\nDo you want to continue (Type y or n) \n");
        ch = scan.next().charAt(0);                        
    } while (ch == 'Y'|| ch == 'y');               
}
}

谢谢龟先生回答这个问题。 这是新编辑的版本:

public Node getMid() {
if (length == 0) return null;
int mid = length / 2;
Node ptr = start;
while (mid-- > 0) {
    ptr = ptr.getLink();
}
return ptr;
  }
   public int getLength()
   {}

 public Node getMid() {}

 public void insert(int val)
{}

 public void display()
{}
   
public class SinglyLinkedList {
    
       public static void main(String[] args)
{             
    Scanner scan = new Scanner(System.in);
    LinkedList list = new LinkedList();         
    char ch;
    do
    {
        System.out.println("\nSingly Linked List\n");                     
        System.out.println("Enter integer element to insert:");
        list.insert( scan.nextInt() );       
        System.out.println("Length of the Linked List: "+ list.getLength() ); 
        list.getMid();      
        list.display();            
        System.out.println("\nDo you want to continue (Type y or n) \n");
        ch = scan.next().charAt(0);                        
    } while (ch == 'Y'|| ch == 'y');               
}
}

希望这能给其他人一些启发。 再次感谢龟先生回答这个问题

由于您已经在 class 中维护了 length 属性,我们可以使用它来找到链表的中间位置。如果列表中的元素数量为偶数,则返回 ceil 如果 1->2->3->4,则返回 3

public Node getMid() {
    if (length == 0) return null;
    int mid = length / 2;
    Node ptr = start;
    while (mid-- > 0) {
        ptr = ptr.getLink();
    }
    return ptr;
}