【问题标题】:Delete all occurrences of a given key in a circular linked list删除循环链表中给定键的所有出现
【发布时间】:2017-11-08 21:39:50
【问题描述】:

我正在尝试删除循环链表中所有出现的给定键,例如:

1 -> 0 -> 1 -> 0

key number = 1 删除所有出现的数字 1 并最终得到:

0 -> 0

但我的代码得到的是:

0 -> 1 -> 0 -> 1

它将头部移动到列表的末尾而不是删除它。

我发现的另一个问题是,如果有 2 个或多个具有相同值的数字彼此相邻,它将总是留下一个,例如:

0 -> 1 -> 1 -> 0

我得到了这个结果

0 -> 1 -> 0

代码

    public void remove(int num) {
        if (isEmpty()) {
            System.out.println("Empty List");
        } else {
            Node currentLink = head;
            Node previousLink = head;
            boolean run = true;

            while (run) {
                if (currentLink.data == num) {
                    currentLink.size--;
                    if (currentLink == head) { //Delete head
                        head = head.next; // Deletes head but then it appears on the end of the list
                    } else
                        previousLink.next = currentLink.next; // Deletes all occurrences of a given key but always leaves one if they are next to each other
                }
                previousLink = currentLink;
                currentLink = currentLink.next;
                if (currentLink == head) run = false;
            }
        }
    }

【问题讨论】:

    标签: java data-structures linked-list


    【解决方案1】:

    您的问题是从列表中删除节点时您没有处理情况。例如,当您删除不是headcurrentLink 时,您没有将currentLink 分配给下一个节点(在移动到下一个节点之前)。 您也没有处理只有一个头的情况。 使用有关如何移动到下一个节点的特定逻辑来分别处理每种情况要容易得多。这是工作代码:

            while (run) {
                if (currentLink.data == num) {
                    currentLink.size--;
                    if (currentLink == head) {
                        if (head == head.next) { //make sure to handle a case where we are removing head from the list that has only one node
                            head = null;
                            break;
                        } else { //we removed a head, move current head to the new one and set currentLink to the next node from head
                            head = head.next;
                            currentLink = head.next;
                            previousLink = head;
                        }
                    } else {
                        previousLink.next = currentLink.next;
                        currentLink = currentLink.next;
                    }
                } else { //no match move on to the next node
                    previousLink = currentLink;
                    currentLink = currentLink.next;
                    if (currentLink == head) run = false;
                }
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-28
      • 1970-01-01
      • 1970-01-01
      • 2015-07-31
      • 1970-01-01
      相关资源
      最近更新 更多