繁体   English   中英

从链接列表中删除所有出现的项目

[英]Remove all occurrences of item from a Linked List

我已经在这个实验室任务工作了几个小时,无法理解为什么这个代码不起作用。 问题是添加方法int removeEvery(T item) ,删除所有出现的item,并将删除的项目数返回到实现链接列表界面的链接列表类。

这是我的代码:它删除了一些项目,但不是全部。

public int removeEvery(T item){
int index = 0;
Node currentNode = firstNode;
for(int i = 1; i <= numberOfEntries; i++)
    {
    System.out.println(currentNode.getData());
        if (item.equals(currentNode.getData())){
            index++;
            remove(i);}
        else{
            currentNode = currentNode.getNextNode();}
    } 
        if(index != 0)
        return index;
    return -1;
}

这是LinkList类中包含的remove方法:

public T remove(int givenPosition)
{
  T result = null;                 // return value

  if ((givenPosition >= 1) && (givenPosition <= numberOfEntries))
  {
     assert !isEmpty();
     if (givenPosition == 1)        // case 1: remove first entry
     {
        result = firstNode.getData();     // save entry to be removed 
        firstNode = firstNode.getNextNode();
        if (numberOfEntries == 1)
           lastNode = null; // solitary entry was removed
        }
        else                           // case 2: givenPosition > 1
        {
           Node nodeBefore = getNodeAt(givenPosition - 1);
           Node nodeToRemove = nodeBefore.getNextNode();
           Node nodeAfter = nodeToRemove.getNextNode();
           nodeBefore.setNextNode(nodeAfter);  // disconnect the node to be removed
           result = nodeToRemove.getData();  // save entry to be removed

           if (givenPosition == numberOfEntries)
              lastNode = nodeBefore; // last node was removed
     } // end if

     numberOfEntries--;
  } // end if

  return result;                   // return removed entry, or 
                                  // null if operation fails
} // end remove

我认为你的问题来自remove(i)

当你删除第i-th元素时,第i+1-th元素变为第i-th ,依此类推:每个元素都被移位。 因此,如果您需要删除列表中位于索引jj+1j-th元素,则删除调用remove(j) j-th元素将移动索引j处的j+1-th元素。 因此删除第二个元素需要再次调用remove(j) ,而不是remove(j+1)

所以你需要在删除后减少i

由于remove方法实际上会减少numberOfEntries ,因此while循环上的条件已正确更新。 所以你需要做的就是更换

if (item.equals(currentNode.getData())) {
    index++;
    remove(i);
}
else {
    currentNode = currentNode.getNextNode();
} 

通过

if (item.equals(currentNode.getData())) {
    index++;
    remove(i--);
}
// update the current node, whether removing it or not
currentNode = currentNode.getNextNode(); 

Iterator.remove()

您正在描述的这个问题显示了Iterator.remove()在使用JDK中的数据结构来浏览可迭代集合并在执行它时删除元素时的用处。

链接列表有一些特殊内容,您可以使用current.getNextNode访问下一个元素,但使用元素索引删除。 您应该查看实现的其余部分如何管理此索引。 第一个元素是否具有索引0或1(以1开始循环)。 删除一个元素的索引会发生什么。 元素是否知道他们的索引?

你可以用类似的东西

  int deletedNodes = 0;
  int currentIndex = 0; // check if 1 or 0
  currentNode = fist;
  while(currentNode != null){ // I guess lastNode.getNextNode() is null
    if(//should remove){
      remove(currentIndex);
      deletedNodes++
      // probably no need to change the index as all element should have been shifted back one index
    } else {
      currentIndex++; // index changes only if no node was deleted
    }
    currentNode = currentNode.getNextNode(); // will work even if it was deleted
  }
return deletedNodes;

删除节点后,如@Vakimshaar建议的那样,您需要递减i因为此索引处的节点已被删除,并且在同一索引处有一个新节点。 除此之外,您还需要更新currentNode引用,因为它仍然指向您刚刚删除的节点,但它应该指向已移动到此索引的新节点。

所以在if (item.equals(currentNode.getData())){ block中你需要执行以下操作:

Node nextNode = currentNode.getNextNode();
index++;
remove(i--);
currentNode = nextNode;

有了这个,您的代码应该正确删除所有出现。

这是一个Java代码,用于删除链接列表中所有项目的出现:

public class LinkedList{
    Node head;
    class Node{
        int data;
        Node next;
        Node(int d){data =d; next = null;}
    }

    public void push(int new_data){
        Node new_node = new Node(new_data);
        new_node.next = head;
        head = new_node;
    }

    public void insertAfter(Node givenNode, int new_data){
        if(givenNode == null)
            System.out.println("Given node cannot be empty");

        Node new_node = new Node(new_data);
        new_node.next = givenNode.next;
        givenNode.next = new_node;
    }

    public void append(int new_data){
        Node new_node = new Node(new_data);
        if(head == null)
            head = new_node;

        else{
        Node last = head;

        while(last.next != null)
            last = last.next;

        last.next = new_node;
    }
    }

    public void printList(){
        Node temp = head;

        while(temp != null){
            System.out.println(temp.data + " ");
            temp = temp.next;
        }
    }

    void deleteNode(int key){
        // Store head node
        Node temp = head, prev=null;
        // If head node itself holds the key or multiple occurrences of key
        while(temp != null && temp.data == key){
            head = temp.next;
            temp = head;
        }
        // Delete occurrences other than head
        while(temp != null){
            // Search for the key to be deleted, keep track of the
            // previous node as we need to change 'prev.next'
            while(temp != null && temp.data != key){
                prev = temp;
                temp = temp.next;
            }
            // If key was not present in linked list
            if(temp == null) return;
            // Unlink the node from linked list
            prev.next = temp.next;
            //Update Temp for next iteration of outer loop
            temp = prev.next;
        }
    }

     public static void main(String[] args){
         LinkedList llist = new LinkedList();

         llist.push(6);
         llist.append(7);
         llist.append(7);
         llist.append(7);
         llist.append(9);
         llist.push(10);
         llist.deleteNode(7);
         llist.printList();
     }
}

输出:

10 6 9

暂无
暂无

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

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