简体   繁体   English

双链表输出已删除的元素

[英]Doubly Linked List outputting removed elements

My code for deleting a player of a doubly linked list works right, but the System.out.print statements don't. 我的删除双向链表播放器的代码可以正常使用,但是System.out.print语句不起作用。 I placed System.outs.print statements before the removeFirst and removeLast because I don't know of a way to output the data that was removed in the nodes so I print it out before I remove. 我将System.outs.print语句放在removeFirst和removeLast之前,因为我不知道一种输出节点中已删除数据的方法,因此我在删除之前将其打印出来。 I know my current method is bad design but I'm unsure of what function to use. 我知道我当前的方法是错误的设计,但是我不确定要使用什么功能。

What conditions do I check for in an if-statement to see if the node has removed successfully? 我要在if语句中检查哪些条件才能查看节点是否已成功删除?

    else if (mChoice.startsWith("4")) {
    System.out.println("What do you want to delete?");

    mChoice = in.nextLine();

    if (mChoice.contains("first")) {
       System.out.println("Removed first player " + rBook.mHead.getData());
       rBook.removeFirst();
    }

    else if (mChoice.contains("last")) {
       System.out.println("Removed last player " + rBook.mHead.mPrev.getData());
       rBook.removeLast();
    }

    else {

       rBook.remove(rBook.searchByName(mChoice));

       // System.out.println(rBook.get() + " removed.");  this line

    }

I would suggest that you modify your remove() function to return the element you just removed. 我建议您修改remove()函数以返回刚刚删除的元素。 So the code you're looking at would look like: 因此,您正在查看的代码如下所示:

Player deleted = rBook.remove(rBook.searchByName(mChoice));
System.out.println(deleted.get() + " removed.");

If you want to store which elements of the list have been removed (to print or undelete them later, for example), then a better design would be either 如果要存储列表中已删除的元素(例如,稍后打印或取消删除它们),则更好的设计可能是

  • only flagging these elements as removed, or 仅将这些元素标记为已删除,或者
  • moving them into another, "history" list. 将它们移到另一个“历史”列表中。

Which of these solutions is better depends on the problems you want to solve. 哪种解决方案更好,取决于您要解决的问题。

If you dont want to change your Player class and its functions try this: 如果您不想更改Player类及其功能,请尝试以下操作:

    else if (mChoice.startsWith("4")) {
    System.out.println("What do you want to delete?");

    mChoice = in.nextLine();
    Player deleted;
    if (mChoice.contains("first")) {
       deleted = rBook.mHead.getData();
       rBook.removeFirst();
       System.out.println("Removed first player " + deleted);
    }

    else if (mChoice.contains("last")) {
       deleted = rBook.mHead.mPrev.getData();
       rBook.removeLast();
       System.out.println("Removed last player " + deleted );

    }

    else {
       deleted = rBook.searchByName(mChoice);
       rBook.remove(searchByName(mChoice));
       System.out.println(deleted + " removed.");

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM