【问题标题】:singly linked list element单链表元素
【发布时间】:2022-01-16 06:59:04
【问题描述】:

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

 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');               
}
}

希望这能给其他人一个想法。 再次感谢 Turtle 先生回答这个问题。

【问题讨论】:

    标签: java data-structures linked-list singly-linked-list


    【解决方案1】:

    由于您已经在类中维护了length 属性,我们可以使用它来查找链表的中间部分。如果 List 中有偶数个元素,则返回 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;
    }
    

    【讨论】:

    • 谢谢,这真的很有帮助。我已经在我的程序中添加了你的代码,当我这样做时 System.out.println("Middle Element of the Linked List:" + list.getMid());。当我添加一个元素时,它一直显示链接列表的中间元素:Node@2d6e8792。你对此有什么建议吗?再次感谢您
    • list.getMid() 返回一个 Node 类型的对象,因此当它传递给 print 方法时,它会在该对象上打印 toString 表示。为了克服这个问题,我们可以在 Node 类中实现 toString 方法来返回数据或打印 list.getMid().data
    • 非常感谢。我的程序没有问题。
    猜你喜欢
    • 1970-01-01
    • 2012-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多