链接列表与比较

时间:2016-02-22 19:15:36

标签: java

您好我需要使用单独的链接实现Hashtable。为此,我实现了一个Node类和LinkedList。链接列表中包含的节点具有属性data,count,指向next的链接以及指向previous.Linked列表的链接,不应具有重复值的值,但如果另一个节点插入了相同的值,则应增加该节点的计数。上面是我的代码,但我无法弄清楚如何实现插入函数,以便在找到重复节点时,计数会增加。

public void insertToHead(Node newNode) {
    newNode.setNext(head);
    head = newNode;
}

public void drop(Node newNode) {
    newNode.getPrev().setNext(newNode.getNext());
}

public void insert(String newData) {
    Node newNode = new Node(newData);
    Node temp = head;
    if (temp == null) {
        insertToHead(newNode);
        newNode.incrementCount();
        nodeCount++;
    } else {
        for(int i=0;i<nodeCount;i++){
            if(temp.getData().equals(newNode.getData())){
                if(temp.getPrev()==null){
                    temp.incrementCount();
                    head=temp;
                }
                if(temp.getNext()==null){
                     temp.getPrev().setNext(null);
                    temp.incrementCount();
                    insertToHead(temp);
                }
                else{
                temp.incrementCount();
                drop(temp);
                insertToHead(temp);
                }
            }
            temp = temp.getNext();
        }
        insertToHead(newNode);
        nodeCount++;
    }
}

1 个答案:

答案 0 :(得分:0)

您需要遍历链接列表,直到找到相等的节点,然后在同一节点上递增计数,而不是之前的计数。如果您在该过程中到达列表的末尾,则进行正常插入。

Node newNode = new Node(newData);
Node temp = head;
if (temp == null) {
    insertToHead(newNode);
    newNode.incrementCount();
    nodeCount++;
} else {
   while(temp != null){
      if(temp.getData().equals(newNode.getData())){
        temp.incrementCount();
        break;
      }
      temp = temp.getNext();
   }

   // didn't find anything, prepend to the list
   if(temp == null){
    insertToHead(newNode);
    nodeCount++;
   }
}